473,398 Members | 2,212 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Getting not derived members of a class

Hello NG,

I want to retrieve the members of a class
with a baseclass.
But the problem is, how to get the non derived
members.

class a:
def who(self):
print "who"
def __init__(self):
self._a = 3

class b(a):
def who1(self):
print "who1"
def __init__(self):
a.__init__(self)
self._b = 4

y=b()

dir (y)
['__doc__', '__init__', '__module__', '_a', '_b', 'who', 'who1']
I need a function which lists only the members of
the "not derived" class (here class B).

_b
_who1
__init__

How can I achieve this?
With the introspect module or so?

many thanks in advance!
--
Franz Steinhaeusler
Aug 1 '05 #1
8 1367
Franz Steinhaeusler wrote:
Hello NG,

I want to retrieve the members of a class
with a baseclass.
But the problem is, how to get the non derived
members.

class a:
def who(self):
print "who"
def __init__(self):
self._a = 3

class b(a):
def who1(self):
print "who1"
def __init__(self):
a.__init__(self)
self._b = 4

y=b()

dir (y)
['__doc__', '__init__', '__module__', '_a', '_b', 'who', 'who1']
I need a function which lists only the members of
the "not derived" class (here class B).

_b
_who1
__init__

How can I achieve this?
With the introspect module or so?


I believe you can't: Both _a and _b end up in y.__dict__ and there's no
way to differentiate between the two depending on the time of their
creation. By the way, these are instance attributes, not class
attributes, so strictly _b is not a member of B, it's just an instance
of y. To see why this is the case, check the following valid (though
highly discouraged) example:

class X:
def __init__(self, x):
if isinstance(x,str):
self._s = x
else:
self._n = x

x1 = X("1")
x2 = X(1)

dir(x1)
['__doc__', '__init__', '__module__', '_s']

dir(x2)
['__doc__', '__init__', '__module__', '_n']
George

Aug 1 '05 #2
On 1 Aug 2005 07:43:22 -0700, "George Sakkis" <gs*****@rutgers.edu>
wrote:
Franz Steinhaeusler wrote:
Hello NG,

I want to retrieve the members of a class
with a baseclass.
But the problem is, how to get the non derived
members.

class a:
def who(self):
print "who"
def __init__(self):
self._a = 3

class b(a):
def who1(self):
print "who1"
def __init__(self):
a.__init__(self)
self._b = 4

y=b()

dir (y)
['__doc__', '__init__', '__module__', '_a', '_b', 'who', 'who1']
I need a function which lists only the members of
the "not derived" class (here class B).

_b
_who1
__init__

How can I achieve this?
With the introspect module or so?


I believe you can't: Both _a and _b end up in y.__dict__ and there's no
way to differentiate between the two depending on the time of their
creation. By the way, these are instance attributes, not class
attributes, so strictly _b is not a member of B, it's just an instance
of y. To see why this is the case, check the following valid (though
highly discouraged) example:

class X:
def __init__(self, x):
if isinstance(x,str):
self._s = x
else:
self._n = x

x1 = X("1")
x2 = X(1)

dir(x1)
['__doc__', '__init__', '__module__', '_s']

dir(x2)
['__doc__', '__init__', '__module__', '_n']
George


Hello George,

thank you for this information.

This is a pity.

The background:
I want to create a code completition for an editor component.
It should distinguish between inherited and non inherited members.
Reason is, that on wxPython, most classes are derived from wxWindow.
For example if I want Code completition for wx.Frame,
I always get the 200 or so suggestions,
whereby most times, I'm only interested in the possible completions of
wx.Frame and maybe wx.TopLevelWindow.
--
Franz Steinhaeusler
Aug 1 '05 #3
On 'y', Python has no way of recording where '_a' and '_b' were set, so
you can't tell whether it comes from class 'a' or 'b'.

You can find the attributes that are defined on 'b' only, though, by
using 'b.__dict__.keys()', or 'y.__class__.__dict__.__keys__()'. This
gives
['__module__', 'who1', '__init__', '__doc__']

If you want to limit yourself to current versions of cpython (because the
bytecode used in cpython is only an implementation detail) and define a 'member
of class a' as one where a.__init__ has a statement like 'self.z = ...', you
can peer into the bytecodes. Something like this:
from dis import HAVE_ARGUMENT, opname
LOAD_FAST = chr(opname.index('LOAD_FAST'))
STORE_ATTR = chr(opname.index('STORE_ATTR'))
HAVE_ARGUMENT = chr(HAVE_ARGUMENT)

def find(cls):
ns = cls.__dict__
result = ns.keys()
init = ns.get('__init__', None)
if not init: return ns
f = ns['__init__'].func_code.co_code
n = ns['__init__'].func_code.co_names
i = 0
while i < len(f) - 6:
if (f[i] == LOAD_FAST and f[i+1] == f[i+2] == '\0'
and f[i+3] == STORE_ATTR):
j = ord(f[i+4]) + 256 * ord(f[i+5])
result.append(n[j])
i += 6
elif f[i] > HAVE_ARGUMENT:
i += 3
else:
i += 1
return result
import franz
franz.find(y.__class__)

['__module__', 'who1', '__init__', '__doc__', '_b']

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD4DBQFC7j7AJd01MZaTXX0RAtwGAJixxnxi/IwFamOKOu0UiytCSuFwAKCNPRvg
At7d3NWBO90k7s1QTCu+MA==
=OssF
-----END PGP SIGNATURE-----

Aug 1 '05 #4
Franz Steinhaeusler wrote:
The background:
I want to create a code completition for an editor component.
It should distinguish between inherited and non inherited members.
Reason is, that on wxPython, most classes are derived from wxWindow.
For example if I want Code completition for wx.Frame,
I always get the 200 or so suggestions,
whereby most times, I'm only interested in the possible completions of
wx.Frame and maybe wx.TopLevelWindow.


You can, of course, always search the base classes and subtract the two sets
(all members)-(members of baseclasses). For example:

cls = wx.Frame

set(dir(cls)) - reduce(set.union, [set(dir(base)) for base in cls.__bases__])

Reinhold
Aug 1 '05 #5
On Mon, 1 Aug 2005 10:24:53 -0500, Jeff Epler <je****@unpythonic.net>
wrote:
On 'y', Python has no way of recording where '_a' and '_b' were set, so
you can't tell whether it comes from class 'a' or 'b'.

You can find the attributes that are defined on 'b' only, though, by
using 'b.__dict__.keys()', or 'y.__class__.__dict__.__keys__()'. This
gives
['__module__', 'who1', '__init__', '__doc__']

If you want to limit yourself to current versions of cpython (because the
bytecode used in cpython is only an implementation detail) and define a 'member
of class a' as one where a.__init__ has a statement like 'self.z = ...', you
can peer into the bytecodes. Something like this:
from dis import HAVE_ARGUMENT, opname
LOAD_FAST = chr(opname.index('LOAD_FAST'))
STORE_ATTR = chr(opname.index('STORE_ATTR'))
HAVE_ARGUMENT = chr(HAVE_ARGUMENT)

def find(cls):
ns = cls.__dict__
result = ns.keys()
init = ns.get('__init__', None)
if not init: return ns
f = ns['__init__'].func_code.co_code
n = ns['__init__'].func_code.co_names
i = 0
while i < len(f) - 6:
if (f[i] == LOAD_FAST and f[i+1] == f[i+2] == '\0'
and f[i+3] == STORE_ATTR):
j = ord(f[i+4]) + 256 * ord(f[i+5])
result.append(n[j])
i += 6
elif f[i] > HAVE_ARGUMENT:
i += 3
else:
i += 1
return result
import franz
franz.find(y.__class__)

['__module__', 'who1', '__init__', '__doc__', '_b']

Jeff


Hello Jeff,

thank you for this desciption.

Well, a little complicated, I must read/try this later,
but it looks promising to get the "last derived class" members ;)
Is there any possibility to simply get out
the classes and baseclasses of a class?

somfunc (y) => class A, B (where B is last).

Ok you can prepare a class, but I need to use
the existing wxPython classes.

--
Franz Steinhaeusler
Aug 1 '05 #6
On Mon, 01 Aug 2005 18:02:20 +0200, Reinhold Birkenfeld
<re************************@wolke7.net> wrote:
Franz Steinhaeusler wrote:
The background:
I want to create a code completition for an editor component.
It should distinguish between inherited and non inherited members.
Reason is, that on wxPython, most classes are derived from wxWindow.
For example if I want Code completition for wx.Frame,
I always get the 200 or so suggestions,
whereby most times, I'm only interested in the possible completions of
wx.Frame and maybe wx.TopLevelWindow.


You can, of course, always search the base classes and subtract the two sets
(all members)-(members of baseclasses). For example:

cls = wx.Frame

set(dir(cls)) - reduce(set.union, [set(dir(base)) for base in cls.__bases__])

Reinhold


Hello Reinhold,

yes, cool, thank you very much!

The optimum would be getting also the other base classes, with the
members, but I think, it is asked to much.

'wx.Frame' ... => CreateStatusBar, ...
'wx.TopLevelWindow' ... => GetIcon, ...
'wx.Window' ... => ...
'wx.EvtHandler' => ...

--
Franz Steinhaeusler
Aug 1 '05 #7
Franz Steinhaeusler wrote:
Is there any possibility to simply get out
the classes and baseclasses of a class?

somfunc (y) => class A, B (where B is last).


If you use "new-style" classes, i.e. classes inheriting from object, it
is trivial:

class X(object):
pass

class Y1(X):
pass

class Y2(X):
pass

class Z(Y1,Y2):
pass
z = Z()
z.__class__.__mro__

(<class '__main__.Z'>, <class '__main__.Y1'>, <class '__main__.Y2'>,
<class '__main__.X'>, <type 'object'>)

Old style classes don't have __mro__, so you have to write it yourself;
in any case, writing old style classes in new code is discouraged.

George

Aug 1 '05 #8
George Sakkis wrote:
z = Z()
z.__class__.__mro__


(<class '__main__.Z'>, <class '__main__.Y1'>, <class '__main__.Y2'>,
<class '__main__.X'>, <type 'object'>)

Old style classes don't have __mro__, so you have to write it yourself;
in any case, writing old style classes in new code is discouraged.


Notice also that George's __mro__ solution returns the bases in reverse
order than what you requested (in your example, you said B should come
last). So use list(reversed(z.__class__.__mro__)) or
z.__class__.__mro__[::-1]

--
Brian Beck
Adventurer of the First Order
Aug 1 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Bhan | last post by:
Using Ptr of derived class to point to base class and viceversa class base { .... } class derived : public base { .... }
6
by: Ken Varn | last post by:
I have an ASP.NET application that is calling a custom class that is trying to parse all of the members of my Page object using Type.GetMembers(). The problem that I am having is that private...
3
by: G.Ashok | last post by:
Hello, The Type.GetProperty() method is throwning "AmbiguousMatchException" when getting value of control class through reflection. The exception occurs under the following cases. 1....
1
by: question | last post by:
I want to know incase there is any performance difference or overhead in calling a base class method and a derived class method. Basically I am talking about simple method that is not overridden...
6
by: Taran | last post by:
Hi All, I tried something with the C++ I know and some things just seem strange. consider: #include <iostream> using namespace std;
3
by: keith.thornhill | last post by:
hey all, got a problem here using Visual basic .net 2005 i have two pairs of base/derived classes. lets call them Base/Derived and BaseStruct/DerivedStruct. i want to be able to instantiate a...
6
by: Bhawna | last post by:
I am into c++ code maintenance for last 3-4 years but recently I am put into design phase of a new project. Being a small comapany I dont have enough guidance from seniors. Currently I am into a...
3
by: Edan | last post by:
I have a base class with protected members (`Base`). The function `MakeBase()` is a member function of another class, that returns a `Base` object initialized with private members of this class. Now...
10
by: blangela | last post by:
If I pass a base class object by reference (likely does not make a difference here that it is passed by reference) as a parameter to a derived class member function, the member function is not...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.