All humans share general basic characteristics and capabilities. A specific human inherits those basic characteristics and capabilities and can develop some other characteristics(attributes) and capabilities(methods).
Attributes can be owned by the class or by the instance(object). Class attributes are owned by the class and they are shared by all the instances of the class.
Class attributes are useful when you want to:
- Store constants that don’t change from an instance to another.
- Have general accountability across all the instances. For example, having a counter that increments
- Define default values that are inherited from the instances of that class.
Class attributes aren’t useful for attributes that are different for each instance.
They are defined outside the methods of the class, commonly just after the class definition. Like this:
'''This is the basic structure of a house''' number_of_houses = 0 -> class attributes def __init__(self):
House.number_of_houses += 1;
Warning: When you change the value of a class attribute, it will change the value of all the instances that inherit from the class attribute.
The class gives a common set of attributes to all the objects created of that class. But each object has its own attributes that don’t share with all the class. Those are called ‘instance attributes’. They belong only to one object. They can be changed without change the class attributes: a human can have red hair, while the others don’t. They allow every instance to have a different value inside each attribute. The values are not accessible from the class, they are accessible only inside the scope of the instance.
Instance attributes are useful to define specific characteristics that are not shared by the other instances of the same class.
They are defined inside the __init__, the constructor function of a class, using ‘self’ like this:
'''This is the basic structure of a house''' def __init__(self):
self.number_of_windows = 0; -> instance attibute
Class attributes are shared by all the instances, that are accessible from all the objects. The instance attributes are owned and accessible only inside the object.
What is the Pythonic way of doing it?
The pythonic way of doing it would be to use getter and setter property methods.
The __dict__ builtin
__dict__ is a predefined method included automatically when we create a class even when we don’t declare it explicitly. It allows seeing all the attributes of any object.