What is the best way to list only the class attributes of a class in Python?

– vars(self) is a powerful command which allows to see all attributers.

Answer by Ruben Duque:

You can use vars(), which will return a dictionary with the class attributes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class MyClass( ):
  def __init__(self):
    self.foo = 9
    self.bar = 10

  def class_attrs(self):
    return vars(self)

c = MyClass()
c.class_attrs() # ==> {'foo': 9, 'bar': 10}

EDIT: Now that Jameson points it out above, I should add that if you subclass MyClass, class_attrs() will return only the attributes for the base class (in this case MyClass) and no attributes from the subclass.

View Answer on Quora

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s