This post will talk about 2 attributes in a Python class: Class attributes and Instance attributes
First, let look at the below Student class:
class Student:
# Class attributes
type = 'Student Type'
id = 'Class Attr ID'
def __init__(self, name='Unknown', age=0, id='Instance Attr ID'):
# Instance attributes.
self.name = name
self.__age = age # Private access attributes.
self.id = id
def setAge(self, age): self.__age = age
def getAge(self): return self.__age
And we create 2 Instance of Student class:
studentA = Student()
studentB = Student('B', 20)
We can access Class Attributes from created Instance or directly from Class:
# Access to Class attributes from Instance or Class
print('Get Type from a certain instance: ' + studentA.type)
print('Get Type from class directly: ' + Student.type)
Output:
Get Type from a certain instance: Student Type
Get Type from class directly: Student Type
In case Class attribute and Instance attribute have same name. Python first look at its Instance attributes, if existed, it will get the Instance attribute. If not existed, it will find Class attribute. Let’s see below code:
# Get the attribute which has same name
print('Get ID from a certain instance: ' + studentA.id)
print('Get ID from class directly: ' + Student.id)
Output:
Get ID from a certain instance: Instance Attr ID
Get ID from class directly: Class Attr ID
So, when should we use Class attributes ?
In my opinions, there are some below cases we can apply Class attributes:
- Using as Constant of a class
class Circle(object):
PI = 3.14
print(Circle.PI) # Output: 3.14
- Tracking all data across all instances of a given class
class Person(object):
names = []
def __init__(self, name):
self.__name = name
Person.names.append(name)
joe = Person('Tom')
bob = Person('Mary')
print Person.names
## ['Tom', 'Mary']
As you see at above code, the Class attributes is used to collect all of created Instances name.
You can find the demo at Github link ClassAttributes.py