InterviewSolution
| 1. |
How do we define class level attributes and methods in a Python class? |
|
Answer» A CLASS has two types of attributes – instance attributes and class atributes. Each object of class may have different values for instance attributes. However class attribute is same for each object of the class. Instance attributes are normally defined and initialized through __init__() method which is executed when object is declared. >>> class MyClass: DEF __init__(self, x,y): self.x=x self.y=y >>> obj1=MyClass(10,20) >>> obj1.x, obj1.y (10, 20) >>> obj2=MyClass(100,200) >>> obj2.x, obj2.y (100, 200)In above example MyClass defines two instance attributes x and y. These attributes are initialized through __init__() method when object is declared. Each object has different values of x and y attributes. Class attribute is defined outside __init__() method (in fact outside any method of the class). It can be assigned value in definition or from within __init__() or any method. However, it’s value is not different for each object. >>> class MyClass: z=10 def __init__(self, x,y): self.x=x self.y=yHere z is not an instance attribute but class attribute defined outside __init__() method. Value of z is same for each object. It is accessed using name of the class. However, accessing with object also shows same value >>> obj1=MyClass(10,20) >>> obj2=MyClass(100,200) >>> MyClass.z 10 >>> obj1.x, obj1.y, obj1.z (10, 20, 10) >>> obj2.x, obj2.y, obj2.z (100, 200, 10Class has instance METHODS as well as class methods. An instance method such as __init__() always has one of the arguments as self which refers to calling object. Instance attributes of calling object are accessed through it. A class method is defined with @classmethod decorator and received class name as argument. >>> class MyClass: z=10 def __init__(self, x,y): self.x=x self.y=y @classmethod def classvar(cls): print (cls.z)The class variable processed inside class method using class name as well as object as reference. It cannot access or process instance attributes. >>> obj1=MyClass(10,20) >>> MyClass.classvar() 10 >>> obj1.classvar() 10Class can have a static method which is defined with @staticmethod decorator. It takes NEITHER a self nor a cls argument. Class attributes are accessed by providing name of class explicitly. >>> class MyClass: z=10 def __init__(self, x,y): self.x=x self.y=y @classmethod def classvar(cls): print (cls.z) @staticmethod def statval(): print (MyClass.z) >>> obj1=MyClass(10,20) >>> MyClass.statval() 10 >>> obj1.statval() 10 |
|