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 8 1663
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(getattr(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
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.)
-Peter
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(getattr(object, s))]
cheers,
Evan
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.) 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(obj, a)) == type(obj)]
# or filter any other way you like
return attributes
--
Steven.
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(getattr(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(Parrot)
# this gives: ['ATTR', 'join']
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,Property):
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.
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.__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.
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
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). This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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.
|
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 =...
|
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
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
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
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
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...
|
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...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
| |