getting all user defined attributes of a class

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Feb 7 08:28:58 CET 2008


On Wed, 06 Feb 2008 15:16:26 -0800, Amit Gupta wrote:

> On Feb 6, 2:55 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>> Amit Gupta schrieb:
>> > I should make class A as:
>> > class A (object) :
>> >   x = 1
>>
>> > Now, x is class attribute and I am looking for some-way to filter non-
>> > user-defined attributes.
>>
>> > e.g.g if I do
>> > for attr in a.__dict__ :
>> >   print attr
>>
>> > I will also get
>>
>> > __module__, __weakref__ and others including "x"
>>
>> Just create an empty class, gather all attribute names from that and
>> then subtract that set of names from the names you get from a "real" class.
>>
>> Dize
> 
> Fine. This is a hack. I am looking if python language itself provides
> any built-in function for this. E.g.:

Why is that a hack!?  What about:

In [369]: def is_special_name(name):
   .....:     return name.startswith('__') and name.endswith('__')
   .....:

In [370]: filter(lambda m: not is_special_name(m[0]), inspect.getmembers(A))
Out[370]: [('x', 1)]

> When I do help on some built-in function, it displays that function is
> built_in. Can that information get accessed using a function? (now,
> don't ask me to store help-output in buffer and grep for built-in).

Yes but it is not built-in.  Have a look at the `inspect` module.

What's the use case?

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list