Whenever we create objects memory is allocated to the data members and value is stored inside them, for example in the following code the memory is allocated to a
only after object emp
is created. We cannot access a
without allocating memory to it.
class Employee:
def __init__(self,first):
self.a=first
emp=Employee('John') #If we remove this statement, we get an error accessing 'a'
print(emp.a)
But in the case of class variables such as shown in the following example;
class Emp:
pi = 3.14
def __init__(self,first):
self.a=first
print(Emp.pi)
We can access the variable pi
without memory allocation. Why is
CodePudding user response:
The class attribute pi
is created when the class is created, not when instances of the class are created.
CodePudding user response:
This is the concept of instance attributes vs class attributes, which is not just in Python.
- Class attributes, from the name itself, are attributes on the class level, and doesn't need an active instance to be accessed. It isn't tied to any instance of the class thus you can access it even without an active object.
- Instance attributes on the other hand, is specific per instance.
This is well documented in Class and Instance Variables:
Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
class Dog: kind = 'canine' # class variable shared by all instances def __init__(self, name): self.name = name # instance variable unique to each instance >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.kind # shared by all dogs 'canine' >>> e.kind # shared by all dogs 'canine' >>> d.name # unique to d 'Fido' >>> e.name # unique to e 'Buddy'
Some other references