Class and instance attribute (Python)

Hex (short for Hexadecimal)— Bobby Yang’s Husky Puppy

Class attributes

Class attributes are attributes that are specific to the class itself, and are shared my all instances of the class. Therefore all instances have the same value. Let’s use the example below, we can generally assume that dogs have 4 legs. This is represented in the class Dog with the variable leg_num. Every time a dog is born (new instance), that dog will have 4 legs.

class Dog:
leg_num = 4
def __init__(self, furclr=0, breed="", name="fido"):
self.__furclr = furclr
self.__breed = breed
self.__name = name

Instance attributes

As opposed to leg_num, dogs have can unique fur color or varies in breeds.

Instance attributes are owned by the specific instances of a class. This means for two different instances, the instance attributes can be different. One dog can be named Hex, a Husky with grey fur. Another dog can be called Diesel, a Shiba mix with brown fur. However, they are both part of the class Dog and have 4 legs.

Python’s class attributes and object attributes are stored in separate dictionaries, as we can see here:

Dictionary of the instance object:

>>> class Dog:
… leg_num = 4
… def __init__(self, name=”fido”, breed=””):
… self.__name = name
… self.__breed = breed

>>> dog1 = Dog(“hex”, “husky”)
>>> dog1.__dict__
{‘_Dog__breed’: ‘husky’, ‘_Dog__name’: ‘hex’}
>>>

Dictionary of the class:

>>> class Dog:
… leg_num = 4
… def __init__(self, name=”fido”, breed=””):
… self.__name = name
… self.__breed = breed

>>> Dog.__dict__
{‘__module__’: ‘__main__’, ‘leg_num’: 4, ‘__init__’: <function __init__ at 0x7f70e5b72050>, ‘__doc__’: None}

This is why you can use the notation, ClassName.AttributeName, to change the values of an attribute. Let’s say there is a genetic mutation for dogs, and all breeds of dogs are born with 6 legs instead of 4. You can change the class attributes, so all instances created before and here on out will have 6 legs (leg_num = 6)

>>> Dog.leg_num = 6
>>> Dog.__dict__
{‘__module__’: ‘__main__’, ‘leg_num’: 6, ‘__init__’: <function __init__ at 0x7f70e5b72050>, ‘__doc__’: None}
>>>

Don’t worry, our buddies are still as adorable as ever. However, if the thought of a 6-legged dog bothers you, worry not! A geneticist found a “cure” to the mutation. So let’s change it back to leg_num = 4

>>> Dog.leg_num = 4
>>> Dog.__dict__
{‘__module__’: ‘__main__’, ‘leg_num’: 4, ‘__init__’: <function __init__ at 0x7f70e5b72050>, ‘__doc__’: None}
>>>

The Pythonic Way — Instance Attributes

  1. Instantiate instance values with default values
  2. Have setter and getter functions
class Dog:
leg_num = 4
def __init__(self, name=”fido”, breed=””):
self.__name = name
self.__breed = breed
   @property
def getName(self):
return self.__name
   @name.setter
def setName(self, value):
self.__name = value