473,624 Members | 2,026 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

listing attributes

Hi there.

I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?

Thanks

Thomas

Feb 14 '06 #1
8 1672
Thomas Girod wrote:
Hi there.

I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?

Thanks

Thomas

Here's a "smart-ass" example:

py> import random
py> class C:
.... def __repr__(self):
.... return "<Im_a_C!>"
....
py> alist = [1,2,3,4,5] + [C() for x in xrange(5)]
py> alist
[1, 2, 3, 4, 5, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>]
py> class Obj:
.... def __repr__(self):
.... return str([getattr(self, o) for o in dir(self) \
.... if isinstance(geta ttr(self, o), C)])
....
py> anobj = Obj()
py> newlist = [choice(alist) for x in xrange(10)]
py> newlist
[<Im_a_C!>, <Im_a_C!>, 5, 1, 5, 4, 4, <Im_a_C!>, <Im_a_C!>, 3]
py> [setattr(anobj, *tup) for tup in zip('abcdefghij ', newlist)]
[None, None, None, None, None, None, None, None, None, None]
py> anobj.a
<Im_a_C!>
py> anobj.b
<Im_a_C!>
py> anobj.c
5
py> anobj.d
1
py> print anobj
[<Im_a_C!>, <Im_a_C!>, <Im_a_C!>, <Im_a_C!>]

James
Feb 14 '06 #2
Thomas Girod wrote:
I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?


Does the __dict__ attribute help you? (Try viewing obj.__dict__ at the
interpreter prompt and see if it has what you expect.
obj.__dict__.ke ys() would be just the names of those attributes.)

-Peter

Feb 14 '06 #3
On Feb.13 18h37, Thomas Girod wrote :
Hi there.

I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.


If you do something like this you should have a list of attributes:

l = dir(object)
l = [s for s in l if s[:2] != '__']
l = [s for s in l if not callable(getatt r(object, s))]

cheers,

Evan
Feb 14 '06 #4
On Mon, 13 Feb 2006 22:18:56 -0500, Peter Hansen wrote:
Thomas Girod wrote:
I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?


Does the __dict__ attribute help you? (Try viewing obj.__dict__ at the
interpreter prompt and see if it has what you expect.
obj.__dict__.ke ys() would be just the names of those attributes.)

class Parrot(object): .... ATTR = None
.... def method(self):
.... return None
.... dir(Parrot) ['ATTR', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute __', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__' , '__repr__', '__setattr__', '__str__', '__weakref__', 'method'] Parrot.__dict__ .keys()

['__module__', 'ATTR', 'method', '__dict__', '__weakref__', '__doc__']

So I guess the answer to that question is, while __dict__ gives less
information than dir, it still gives too much.

The thing to remember is that methods are attributes too, so it is a
little hard to expect Python to magically know which attributes you want
to see and which you don't. Although, I don't think it is too much to
expect Python to distinguish methods from non-method attributes.

However it is easy to use introspection to get what you need.

def introspect(obj) :
attributes == dir(obj)
# get rid of attributes that aren't the right type
attributes = [a for a in attributes if \
type(getattr(ob j, a)) == type(obj)]
# or filter any other way you like
return attributes

--
Steven.

Feb 14 '06 #5
Steven D'Aprano wrote:
However it is easy to use introspection to get what you need.


So just for completeness sake, what Thomas probably wants is the following:

from types import MethodType

def attributes(obj) :
return [attr for attr in dir(obj)
if not attr.startswith ('__')
and not isinstance(geta ttr(obj, attr), MethodType)]

# Example:

class Parrot(object):
ATTR = None
join = ''.join # callable, but not a method of Parrot
def aMethod(self):
return ATTR

print attributes(Parr ot)

# this gives: ['ATTR', 'join']
Feb 14 '06 #6
Thanks a lot for all your answers !

Thanks to you I resolved this problem. Here is what i've done :

[...]
for (_,v) in getmembers(self ):
if isinstance(v,Pr operty):
st += "\t%s\n" % str(v)
[...]

as all the attributes I want to get are instances of Property or a
subclass of Property, it does the trick.

Feb 14 '06 #7
Steven D'Aprano wrote:
On Mon, 13 Feb 2006 22:18:56 -0500, Peter Hansen wrote:
Thomas Girod wrote:
I'm trying to get a list of attributes from a class. The dir() function
seems to be convenient, but unfortunately it lists to much - i don't
need the methods, neither the built-in variables.

In fact, all my variables are referencing to objects of the same type.
Can anyone suggest me a way to get this list of variables ?


Does the __dict__ attribute help you? (Try viewing obj.__dict__ at the
interpreter prompt and see if it has what you expect.
obj.__dict__. keys() would be just the names of those attributes.)

Parrot.__di ct__.keys()
['__module__', 'ATTR', 'method', '__dict__', '__weakref__', '__doc__']

So I guess the answer to that question is, while __dict__ gives less
information than dir, it still gives too much.


I was making the perhaps mistaken assumption that the OP was another of
those who meant "object" when he said "class" (though I could perhaps
have asked that explicitly).

If that were the case, I think __dict__ could be what he wanted. (I'm
still not sure what he wanted, even after reading his response, since I
can't see what his classes or objects look like...)
class Parrot(object): .... ATTR = None
.... def method(self):
.... return None
.... polly = Parrot()
polly.foo = '1'
polly.bar = 'baz'
polly.__dict__

{'foo': '1', 'bar': 'baz'}

-Peter

Feb 14 '06 #8
You are right, using __dict__ is what i needed.

But I chose the solution explained before because i don't want to list
all attributes of the object, only attributes that are instances of the
class Property (or a subclass of it).

Feb 15 '06 #9

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

Similar topics

1
736
by: Miguel Gonzalez | last post by:
Hello. Where could I find a table with all the CSS attributes and a list of its different values. Thanks.
19
3304
by: SU News Server | last post by:
I've struggled with this for quite a while and I'm am just not sure what is going on. I have the following code import os def buildList( directory='/Users/mkonrad' ) dirs = listing = os.listdir(directory)
3
1738
by: Rohit Sharma | last post by:
Hi all.. ..NET + MSXML platform....VB Need to build a list of all the entities and attributes to allow the user to do search...how can i do that from the schema ?? Cheers Rohit
3
2039
by: David Jacques | last post by:
I am trying to get a list of all files of a certain extension type on disk to do some processing in a loop. The code needs to be portable to UNIX, so I need to use plain c functionality. Does anyone know of a way to do this ? Any URLs, code snippets, etc ?
2
1312
by: Kurt Schroeder | last post by:
I have a simple directoy list bound to a datagrid. I can get the file names, but is there a way to get the file information from system.io.directory. I'd like to get file size, creation date, and dropping off the the path from the file name would not hurt. This can all be done, i know, but i'd like some advice on the quick simple way. thanks kes (code) Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)...
1
5317
by: vhg119 | last post by:
Can someone please link me to some resource listing all the user attributes names? I'm writing some C# code using the System.DirectoryServices assembly. This particular function is suppose to search for a user by "displayName" and set the users phone numbers. I have an incomplete list of Properties: displayName, givenName, sAMAccountName... I need the property names for: "Telephone number" in the General tab of Active Directory Users...
1
1494
by: Johnny Jörgensen | last post by:
I've got a serious problem. I've got Visual Studio 2005 installed, and of course I'm using the Pretty Listing formatting function. When I start up VS, everything is fine, but after a while (which can be one minute or one hour) the Pretty Listing starts acting weird. For instance, if I start writing "for...", it changes it to f(o) r" or something like that. When that starts happening, I can't code at all and have to restart VS. Sometimes...
2
1164
by: John Geddes | last post by:
If I create an object using a constructor function, and then specify attributes using the format "this.attrib1 = 123;" - then it is easy enough to list the VALUES (using a loop like "for thisAttrib in thisObject"), but for faster debugging, I would like also to be able to list the NAMES of the attributes using a similar loop. Is there a way to reference the attribute name specified in the "this." statement, ie the "attrib1" bit of...
5
3483
by: jain236 | last post by:
HI every body, i am always getting the following error while parsing a directory . i am reading a directory by doing ls and trying to find out the name,type,size, mtime and mode of files from the directory my @valeu =@{$Files}; foreach my $file (parse_dir(\@valeu)) { @Files = $ftp->ls('-lR');
0
8174
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8624
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8336
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4176
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2607
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1485
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.