195

I want to get the attributes of a class, say:

class MyClass():
  a = "12"
  b = "34"

  def myfunc(self):
    return self.a

using MyClass.__dict__ gives me a list of attributes and functions, and even functions like __module__ and __doc__. While MyClass().__dict__ gives me an empty dict unless I explicitly set an attribute value of that instance.

I just want the attributes, in the example above those would be: a and b

Marco
  • 1,377
  • 15
  • 18
Mohamed Khamis
  • 7,731
  • 10
  • 38
  • 58

20 Answers20

189

Try the inspect module. getmembers and the various tests should be helpful.

EDIT:

For example,

class MyClass(object):
    a = '12'
    b = '34'
    def myfunc(self):
        return self.a

>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
 ('__dict__',
  <dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
   '__doc__': None,
   '__module__': '__main__',
   '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
   'a': '34',
   'b': '12',
   'myfunc': <function __main__.myfunc>}>),
 ('__doc__', None),
 ('__module__', '__main__'),
 ('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
 ('a', '34'),
 ('b', '12')]

Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.

>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]

...and the more complicated of which can include special attribute name checks or even metaclasses ;)

adiro
  • 370
  • 1
  • 3
  • 17
Matt Luongo
  • 14,371
  • 6
  • 53
  • 64
  • yup this is great! I used this: `attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))` `print [a[0] for a in attributes if '_' not in a[0]]` – Mohamed Khamis Jan 30 '12 at 10:09
  • 8
    Be careful- that won't include attributes `like_this`! It'll also avoid "private" attributes, which you might've done on purpose. – Matt Luongo Jan 30 '12 at 16:29
  • Hi, I loved that too with a slight clarification : in the expression `inspect.getmembers(MyClass, ...`, `MyClass` can be replaced by a class or an object, and if you need the list of the values of your objects, you must replace `MyClass` by your object variable (or `self` if you put this expression in a `def __repr__()` method like me). – herve-guerin Sep 15 '17 at 20:23
  • I used this (in Python3) to get a function that looked for the '__dict__' value: `i = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a))); z = [_[1] for _ in i if _[0] in '__dict__'][0]` and then it's just a matter of getting the keys from z. – double0darbo Nov 11 '19 at 21:19
  • Is it possible to get the `attributes` in the same order that they were stated inside the `class`? This code is returning me the `attributes` in alphabetical order. – Daniel Arges Jan 31 '21 at 15:14
82
def props(cls):   
  return [i for i in cls.__dict__.keys() if i[:1] != '_']

properties = props(MyClass)
Doug
  • 32,844
  • 38
  • 166
  • 222
51

Getting only the instance attributes is easy.
But getting also the class attributes without the functions is a bit more tricky.

Instance attributes only

If you only have to list instance attributes just use
for attribute, value in my_instance.__dict__.items()

>>> from __future__ import (absolute_import, division, print_function)
>>> class MyClass(object):
...   def __init__(self):
...     self.a = 2
...     self.b = 3
...   def print_instance_attributes(self):
...     for attribute, value in self.__dict__.items():
...       print(attribute, '=', value)
...
>>> my_instance = MyClass()
>>> my_instance.print_instance_attributes()
a = 2
b = 3
>>> for attribute, value in my_instance.__dict__.items():
...   print(attribute, '=', value)
...
a = 2
b = 3

Instance and class attributes

To get also the class attributes without the functions, the trick is to use callable().

But static methods are not always callable!

Therefore, instead of using callable(value) use
callable(getattr(MyClass, attribute))

Example

from __future__ import (absolute_import, division, print_function)

class MyClass(object):
   a = "12"
   b = "34"               # class attributes

   def __init__(self, c, d):
     self.c = c
     self.d = d           # instance attributes

   @staticmethod
   def mystatic():        # static method
       return MyClass.b

   def myfunc(self):      # non-static method
     return self.a

   def print_instance_attributes(self):
     print('[instance attributes]')
     for attribute, value in self.__dict__.items():
        print(attribute, '=', value)

   def print_class_attributes(self):
     print('[class attributes]')
     for attribute in MyClass.__dict__.keys():
       if attribute[:2] != '__':
         value = getattr(MyClass, attribute)
         if not callable(value):
           print(attribute, '=', value)

v = MyClass(4,2)
v.print_class_attributes()
v.print_instance_attributes()

Note: print_class_attributes() should be @staticmethod
      but not in this stupid and simple example.

Result for

$ python2 ./print_attributes.py
[class attributes]
a = 12
b = 34
[instance attributes]
c = 4
d = 2

Same result for

$ python3 ./print_attributes.py
[class attributes]
b = 34
a = 12
[instance attributes]
c = 4
d = 2
Silveri
  • 4,836
  • 3
  • 35
  • 44
oHo
  • 51,447
  • 27
  • 165
  • 200
  • 1
    In Python3.8, the code gives the result of `class attributes` same as `instance attributes`. – Qinsheng Zhang May 07 '21 at 18:57
  • 1
    Great answer. For those wondering about `__dict__` vs `vars()`, see https://stackoverflow.com/q/21297203 – djvg Feb 23 '22 at 09:16
  • 1
    There was an edit that broke this example for more than a year. The `print_class_attributes` function has to reference `MyClass` directly, unless you use the alternative of making it a `@classmethod` in which case it could use `self`/`cls` instead. – Silveri Jun 23 '22 at 06:43
35

myfunc is an attribute of MyClass. That's how it's found when you run:

myinstance = MyClass()
myinstance.myfunc()

It looks for an attribute on myinstance named myfunc, doesn't find one, sees that myinstance is an instance of MyClass and looks it up there.

So the complete list of attributes for MyClass is:

>>> dir(MyClass)
['__doc__', '__module__', 'a', 'b', 'myfunc']

(Note that I'm using dir just as a quick and easy way to list the members of the class: it should only be used in an exploratory fashion, not in production code)

If you only want particular attributes, you'll need to filter this list using some criteria, because __doc__, __module__, and myfunc aren't special in any way, they're attributes in exactly the same way that a and b are.

I've never used the inspect module referred to by Matt and Borealid, but from a brief link it looks like it has tests to help you do this, but you'll need to write your own predicate function, since it seems what you want is roughly the attributes that don't pass the isroutine test and don't start and end with two underscores.

Also note: by using class MyClass(): in Python 2.7 you're using the wildly out of date old-style classes. Unless you're doing so deliberately for compatibility with extremely old libraries, you should be instead defining your class as class MyClass(object):. In Python 3 there are no "old-style" classes, and this behaviour is the default. However, using newstyle classes will get you a lot more automatically defined attributes:

>>> class MyClass(object):
        a = "12"
        b = "34"
        def myfunc(self):
            return self.a
>>> dir(MyClass)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'myfunc']
Ben
  • 68,572
  • 20
  • 126
  • 174
  • 8
    One cannot depend on `dir()`: "_Because dir() is supplied primarily as a convenience for use at an interactive prompt, **it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names**, and **its detailed behavior may change across releases**._" (see [documentation of `dir()`](http://docs.python.org/library/functions.html#dir)). – Tadeck Jan 30 '12 at 01:31
  • @Tadeck: Good point. I was using it illustratively rather than suggesting it as a solution, since it wouldn't easily allow you to filter the attributes based on what they refer to. But I should be more explicit about that. – Ben Jan 30 '12 at 02:02
12

MyClass().__class__.__dict__

However, the "right" was to do this is via the inspect module.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • 12
    `MyClass().__class__.__dict__` == `MyClass.__dict__` – yak Jan 30 '12 at 04:03
  • 5
    @yak's comment isn't quite true. See the following about the differences between class and instance attributes. See http://stackoverflow.com/questions/35805/why-is-my-instance-variable-not-in-dict. – sholsapp Feb 16 '15 at 18:33
  • 3
    @sholsapp actually @yak is right. The link you provided says that `MyClass().__class__.__dict__ != MyClass().__dict__`, but yak is not including the parentheses on the right-hand side, in the case of which s/he is correct – Shadi Nov 15 '19 at 08:49
4
import re

class MyClass:
    a = "12"
    b = "34"

    def myfunc(self):
        return self.a

attributes = [a for a, v in MyClass.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

For an instance of MyClass, such as

mc = MyClass()

use type(mc) in place of MyClass in the list comprehension. However, if one dynamically adds an attribute to mc, such as mc.c = "42", the attribute won't show up when using type(mc) in this strategy. It only gives the attributes of the original class.

To get the complete dictionary for a class instance, you would need to COMBINE the dictionaries of type(mc).__dict__ and mc.__dict__.

mc = MyClass()
mc.c = "42"

# Python 3.5
combined_dict = {**type(mc).__dict__, **mc.__dict__}

# Or Python < 3.5
def dict_union(d1, d2):
    z = d1.copy()
    z.update(d2)
    return z

combined_dict = dict_union(type(mc).__dict__, mc.__dict__)

attributes = [a for a, v in combined_dict.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]
JD Graham
  • 189
  • 2
  • 3
4

Python 2 & 3, whitout imports, filtering objects by their address

Solutions in short:

Return dict {attribute_name: attribute_value}, objects filtered. i.e {'a': 1, 'b': (2, 2), 'c': [3, 3]}

{k: val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)}

Return list [attribute_names], objects filtered. i.e ['a', 'b', 'c', 'd']

[k for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)]

Return list [attribute_values], objects filtered. i.e [1, (2, 2), [3, 3], {4: 4}]

[val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)]

Not filtering objects

Removing the if condition. Return {'a': 1, 'c': [3, 3], 'b': (2, 2), 'e': <function <lambda> at 0x7fc8a870fd70>, 'd': {4: 4}, 'f': <object object at 0x7fc8abe130e0>}

{k: val for k, val in self.__dict__.items()}

Solution in long

As long as the default implementation of __repr__ is not overridden the if statement will return True if the hexadecimal representation of the location in memory of val is in the __repr__ return string.

Regarding the default implementation of __repr__ you could find useful this answer. In short:

def __repr__(self):
    return '<{0}.{1} object at {2}>'.format(
      self.__module__, type(self).__name__, hex(id(self)))

Wich returns a string like:

<__main__.Bar object at 0x7f3373be5998>

The location in memory of each element is got via the id() method.

Python Docs says about id():

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.


Try by yourself

class Bar:

    def __init__(self):

        self.a = 1
        self.b = (2, 2)
        self.c = [3, 3]
        self.d = {4: 4}
        self.e = lambda: "5"
        self.f = object()

    #__str__ or __repr__ as you prefer
    def __str__(self):
        return "{}".format(

            # Solution in Short Number 1
            {k: val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)}

        )

# Main
print(Bar())

Output:

{'a': 1, 'c': [3, 3], 'b': (2, 2), 'd': {4: 4}}

Note:

  • Tested with Python 2.7.13 and Python 3.5.3

  • In Python 2.x .iteritems() is preferred over .items()

Marco D.G.
  • 2,317
  • 17
  • 31
3

If you want to "get" an attribute, there is a very simple answer, which should be obvious: getattr

class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
    return self.a

>>> getattr(MyClass, 'a')
'12'

>>> getattr(MyClass, 'myfunc')
<function MyClass.myfunc at 0x10de45378>

It works dandy both in Python 2.7 and Python 3.x.

If you want a list of these items, you will still need to use inspect.

fralau
  • 3,279
  • 3
  • 28
  • 41
  • 1
    Is that answer too simple and too correct to deserve any points, and should even deserve bad points? It seems that economy and simplicity no longer pay off nowadays. – fralau May 01 '20 at 07:32
  • 3
    He wants to _list_ attributes, not to _get_. See an example at the lower part of the question. – ogurets Sep 26 '21 at 17:37
  • @ogurets It is clearly stated in his question that he wants to _get_ attributes, not to _list_ them (as for _listing_ see, the lower part of my answer). – fralau Aug 07 '22 at 03:17
2

I don't know if something similar has been made by now or not, but I made a nice attribute search function using vars(). vars() creates a dictionary of the attributes of a class you pass through it.

class Player():
    def __init__(self):
        self.name = 'Bob'
        self.age = 36
        self.gender = 'Male'

s = vars(Player())
#From this point if you want to print all the attributes, just do print(s)

#If the class has a lot of attributes and you want to be able to pick 1 to see
#run this function
def play():
    ask = input("What Attribute?>: ")
    for key, value in s.items():
        if key == ask:
            print("self.{} = {}".format(key, value))
            break
    else:
        print("Couldn't find an attribute for self.{}".format(ask))

I'm developing a pretty massive Text Adventure in Python, my Player class so far has over 100 attributes. I use this to search for specific attributes I need to see.

  • unfortunately vars() won't return class attributes – user2682863 Aug 27 '19 at 01:37
  • Have you tried running the code I've posted? Vars can definitely return class attributes. Show me an example of how it doesn't? Maybe my code is incorrect. But assigning vars() to a variable and using a key,value search through that variable can return class attributes. – Corey Bailey Aug 28 '19 at 13:32
  • class T:x=1; t = T(); vars(t) – user2682863 Aug 28 '19 at 15:49
  • You'll have to wait till I get off work to properly show you. But your code is incorrect. Your class object needs to define __init__(self) and x needs to be self.x=1. Then assign t = T() and use print(vars(t)) and it will show you a dictionary of all the class attributes. – Corey Bailey Aug 29 '19 at 20:37
  • 1
    no, those are instance attributes not class attributes, many sub-classes never call __init__. As I said, vars() won't return class attributes, you need to use dir() or inspect.getmembers() – user2682863 Aug 29 '19 at 23:04
  • Ah I see what you're saying now, I was misunderstanding what you meant by class attributes, my bad. But I really don't see any clarity in dir() or inspect.getmembers(). Using vars() for class instances shows actual self attributes which is readable compared to the other methods. With dir() all I see is a bunch of nonsense for a class with 1 attribute. What I like seeing is that 1 actual attribute. Sorry for the misunderstanding though. – Corey Bailey Aug 30 '19 at 02:20
2

This can be done without inspect, I guess.

Take the following class:

 class Test:
   a = 1
   b = 2

   def __init__(self):
     self.c = 42

   @staticmethod
   def toto():
     return "toto"

   def test(self):
     return "test"

Looking at the members along with their types:

t = Test()
l = [ (x, eval('type(x.%s).__name__' % x)) for x in dir(a) ]

... gives:

[('__doc__', 'NoneType'),
 ('__init__', 'instancemethod'),
 ('__module__', 'str'),
 ('a', 'int'),
 ('b', 'int'),
 ('c', 'int'),
 ('test', 'instancemethod'),
 ('toto', 'function')]

So to output only the variables, you just have to filter the results by type, and names not starting with '__'. E.g.

filter(lambda x: x[1] not in ['instancemethod', 'function'] and not x[0].startswith('__'), l)

[('a', 'int'), ('b', 'int'), ('c', 'int')] # actual result

That's it.

Note: if you're using Python 3, convert the iterators to lists.

If you want a more robust way to do it, use inspect.

Carmellose
  • 4,815
  • 10
  • 38
  • 56
1

My solution to get all attributes (not methods) of a class (if the class has a properly written docstring that has the attributes clearly spelled out):

def get_class_attrs(cls):
    return re.findall(r'\w+(?=[,\)])', cls.__dict__['__doc__'])

This piece cls.__dict__['__doc__'] extracts the docstring of the class.

Princy
  • 333
  • 3
  • 11
Henry On
  • 19
  • 2
  • Important note: This will not work in some cases. It only works for classes with properly written docstrings that has the attributes clearly spelled out. – Princy Feb 05 '21 at 20:23
1

I recently needed to figure out something similar to this question, so I wanted to post some background info that might be helpful to others facing the same in future.

Here's how it works in Python (from https://docs.python.org/3.5/reference/datamodel.html#the-standard-type-hierarchy):

MyClass is a class object, MyClass() is an instance of the class object. An instance's __dict__ only hold attributes and methods specific to that instance (e.g. self.somethings). If an attribute or method is part of a class, it is in the class's __dict__. When you do MyClass().__dict__, an instance of MyClass is created with no attributes or methods besides the class attributes, thus the empty __dict__

So if you say print(MyClass().b), Python first checks the new instance's dict MyClass().__dict__['b'] and fails to find b. It then checks the class MyClass.__dict__['b'] and finds b.

That's why you need the inspect module, to emulate that same search process.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Scott Howard
  • 313
  • 2
  • 8
  • 2
    Scott - A comment posted as an answer must get deleted, otherwise we'd be drowning in them. However, a partial answer or "helpful nudge" towards a solution is _still an answer_. You'll see how I reworded your post; hopefully I retained your intent. If not, you can further [edit] it into shape. Cheers! – Mogsdad Mar 09 '16 at 18:35
1

You can use dir() in a list comprehension to get the attribute names:

names = [p for p in dir(myobj) if not p.startswith('_')]

Use getattr() to get the attributes themselves:

attrs = [getattr(myobj, p) for p in dir(myobj) if not p.startswith('_')]
Rotareti
  • 49,483
  • 23
  • 112
  • 108
1

Why do you need to list the attributes? Seems that semantically your class is a collection. In this cases I recommend to use enum:

import enum

class myClass(enum.Enum):
     a = "12"
     b = "34"

List your attributes? Nothing easier than this:

for attr in myClass:
    print("Name / Value:", attr.name, attr.value)
VengaVenga
  • 680
  • 1
  • 10
  • 13
0

two function:

def get_class_attr(Cls) -> []:
    import re
    return [a for a, v in Cls.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

def get_class_attr_val(cls):
    attr = get_class_attr(type(cls))
    attr_dict = {}
    for a in attr:
        attr_dict[a] = getattr(cls, a)
    return attr_dict

use:

>>> class MyClass:
    a = "12"
    b = "34"
    def myfunc(self):
        return self.a

>>> m = MyClass()
>>> get_class_attr_val(m)
{'a': '12', 'b': '34'}
redscarf
  • 1
  • 1
0

The following is what I want.

Test Data

class Base:
    b = 'b'


class MyClass(Base):
    a = '12'

    def __init__(self, name):
        self.name = name

    @classmethod
    def c(cls):
        ...

    @property
    def p(self):
        return self.a

    def my_fun(self):
        return self.name
print([name for name, val in inspect.getmembers(MyClass) if not name.startswith('_') and not callable(val)])  # need `import inspect`
print([_ for _ in dir(MyClass) if not _.startswith('_') and not callable(getattr(MyClass, _))])
# both are equ: ['a', 'b', 'p']

my_instance = MyClass('c')
print([_ for _ in dir(my_instance) if not _.startswith('_') and not callable(getattr(my_instance, _))])
# ['a', 'b', 'name', 'p']
Carson
  • 6,105
  • 2
  • 37
  • 45
0

Quick function to get attribute that aren't magic properties and its value.

The usage of this utility recipe is just to get a quick introspection of a Class or Object without going deep in code or Documentations. When I used it I just wanted to know that stuff that class has and devide what is a function and what is not, obviously I don't remember why thought I needed.

For the example, I used Python Faker but anything can be used really.

from faker import Faker
fake = Faker()

def get_class_props(cls):
    for p in dir(cls):
        if not p.startswith('__'):
            attr_value = getattr(cls, p)
            if p.startswith('_'):
                 print(f'- {p} (private): {attr_value}')
            else:
                print(f'- {p}: {attr_value}')

get_class_props(fake)

- _factories (private): [<faker.generator.Generator object at 0x00000138D01D28C8>]
# - _factory_map (private): OrderedDict([('en_US', <faker.generator.Generator object at 0x00000138D01D28C8>)])
# - _locales (private): ['en_US']
# - _map_provider_method (private): <bound method Faker._map_provider_method of <faker.proxy.Faker object at 0x00000138D017AD88>>
# - _select_factory (private): <bound method Faker._select_factory of <faker.proxy.Faker object at 0x00000138D017AD88>>
# - _unique_proxy (private): <faker.proxy.UniqueProxy object at 0x00000138D017A308>
# - _weights (private): None
# - aba: <bound method Provider.aba of <faker.providers.bank.en_GB.Provider object at 0x00000138D281DBC8>>
# - add_provider: <bound method Generator.add_provider of <faker.generator.Generator object at 0x00000138D01D28C8>>
# - address: <bound method Provider.address of <faker.providers.address.en_US.Provider object at 0x00000138D2810DC8>>
# ...

To clean up the funcitions definitions,use this variations instead, wich defines 'function' whatever is a callable

from faker import Faker
fake = Faker()

def get_class_props(cls):
    for p in dir(cls):

        if not p.startswith('__'):
            attr_value = getattr(cls, p)
            is_function = callable(attr_value)

            if p.startswith('_'):
                 print(f'- {p} (private): {attr_value if not is_function else "funciton"}')
            else:
                print(f'- {p}: {attr_value if not is_function else "funciton"}')


- _factories (private): [<faker.generator.Generator object at 0x0000018A11D49C48>]
- _factory_map (private): OrderedDict([('en_US', <faker.generator.Generator object at 0x0000018A11D49C48>)])
- _locales (private): ['en_US']
- _map_provider_method (private): funciton
- _select_factory (private): funciton
- _unique_proxy (private): <faker.proxy.UniqueProxy object at 0x0000018A11D49748>
- _weights (private): None
- aba: funciton
get_class_props(fake)
Federico Baù
  • 6,013
  • 5
  • 30
  • 38
  • 1
    This is a good answer! But it would be even more helpful if a real class was used (why not the OP's example?). It's not obvious what Faker does, or what attributes actually come from the generated class. – MEMark Nov 03 '21 at 09:15
  • 1
    @MEMark This example is just a quick dirty utility recipe to get the attribute of a Class or Object, that's it really. When I used it is because I was probably looking what stuff the [Faker](https://faker.readthedocs.io/en/master/) had instead of going deep in documentation or code. Indeed, by the time I did not know how to implement Faker objs, that's why It can be used anywhere. I would say is just for a quick introspection. By the way I added some more clarity to the answer – Federico Baù Nov 03 '21 at 11:12
0

To add filtering features to the answers above :

import inspect
import re

def getClassMembers(obj, name=None, mbrcat='all'):
    # name : filter by attribute name
    # mbrcat : filter members by items category : all, methods or attributes
    dic_cat= { 
        'all' : lambda a: a, 
        'meth' : lambda a: inspect.isroutine(a), 
        'attr' : lambda a:  not(inspect.isroutine(a)) 
      } 
    return [str(_name)+'  :  '+str(member)  
            for _name, member in inspect.getmembers(obj, dic_cat[mbrcat])  
            if ((name==None) or (name in _name)) and (not(re.search(r'(^\_\_|\_\_$)' ,_name))) ]

Call #1:

getClassMembers(myClass.browse(264917),'state')

#Output:
['_compute_activity_state  :  <bound method xxx._compute_activity_state of classXXX >'
 'extract_state  :  no_extract_requested',
 'invoice_payment_state  :  paid',
 'state  :  posted'
] 

Call #2:

getClassMembers(myClass.browse(264917),'state','meth')

#Output:
['_compute_activity_state  :  <bound method xxx._compute_activity_state of classXXX >'
] 

Call #3:

getClassMembers(myClass.browse(264917),'state','attr')
#Ouput:
[
 'extract_state  :  no_extract_requested',
 'invoice_payment_state  :  paid',
 'state  :  posted'
] 
sylvain
  • 853
  • 1
  • 7
  • 20
-3

I know this was three years ago, but for those who are to come by this question in the future, for me:

class_name.attribute 

works just fine.

Jim Jam
  • 713
  • 4
  • 10
  • 22
-3

You can use MyClass.__attrs__. It just gives all the attributes of that class. Nothing more.

jimxliu
  • 11