Code:
class MyClass:
class_attribute = 10
def __init__(self, value):
self.instance_attribute = value
obj = MyClass(20)
print(obj.class_attribute)
Solution and Explanation:
Let's break down the code step by step:
Class Definition
class MyClass:
This line defines a new class named MyClass. A class is a blueprint for creating objects (instances).
Class Attribute
class_attribute = 10
Within the class definition, class_attribute is defined. This is a class attribute, which means it is shared by all instances of the class. You can access this attribute using the class name (MyClass.class_attribute) or any instance of the class (obj.class_attribute).
Constructor Method
def __init__(self, value):
self.instance_attribute = value
This is the constructor method (__init__). It is called when an instance of the class is created. The self parameter refers to the instance being created. The value parameter is passed when creating an instance. Inside the method, self.instance_attribute = value sets an instance attribute named instance_attribute to the value passed to the constructor.
Creating an Instance
obj = MyClass(20)
Here, an instance of MyClass is created, and the value 20 is passed to the constructor. This means obj.instance_attribute will be set to 20.
Accessing the Class Attribute
print(obj.class_attribute)
This line prints the value of class_attribute using the instance obj. Since class_attribute is a class attribute, its value is 10.
Summary
class_attribute is a class attribute shared by all instances of MyClass.
instance_attribute is an instance attribute specific to each instance.
obj = MyClass(20) creates an instance with instance_attribute set to 20.
print(obj.class_attribute) prints 10, the value of the class attribute.
So, the output of the code will be:
10
0 Comments:
Post a Comment