Python: Class Attributes

By Xah Lee. Date: .

Class attributes

In python, variable and methods of a object are called attributes.

attributes is accessed by object_name.attribute_name.

Type of attributes

Magic attributes

there are special attributes, sometimes called underscore attributes.

here are some useful special attributes.

__dict__

A dictionary of instance attributes of the object.

__bases__

A tuple that contains the class's immediate (direct) base classes, in the order they were listed in the parameters of class definition.

__mro__

A tuple of classes in order of method resolution.

mro stands for Method Resolution Order.

Name, doc, module

__name__

Name of the class

__doc__

Doc string of the object, or None

__module__

Module name in which the class is defined. If top level, it's "__main__"

Example

class Dog:
    "A class example"

    legs = 4

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

    def number_of_legs(self):
        return self.legs

print(Dog.__doc__)
# A class example

print(Dog.__name__)
# Dog

print(Dog.__module__)
# __main__


print(Dog.__dict__)

# {'__module__': '__main__',
#  '__firstlineno__': 1,
#  '__doc__': 'A class example',
#  'legs': 4,
#  '__init__': <function Dog.__init__ at 0x000002A105D6F1C0>,
#  'number_of_legs': <function Dog.number_of_legs at 0x000002A105D6F270>,
#  '__static_attributes__': ('eye_color',
# ),
#  '__dict__': <attribute '__dict__' of 'Dog' objects>,
#  '__weakref__': <attribute '__weakref__' of 'Dog' objects>}


print(Dog.__bases__)
# (<class 'object'>,)

print(Dog.__mro__)
# (<class '__main__.Dog'>, <class 'object'>)

Python. Class and Object