📖 generic · 12th TN - English Medium · COMPUTER SCIENCE · Page 176question

PYTHON CLASSES AND OBJECTS · Part 4

Chapter 3: 4 · COMPUTER SCIENCE

self keyword. In the above example, we use constructor to define instance variable. Note class Sample: num= class variable def (self, var): Sample.num+= self.var=var instance variable print("The object value is = ", self.var) print("The count of object created = ", Sample.num) S1=Sample( ) S2=Sample( ) S3=Sample( ) Example : Program to illustrate class variable to keep count of number of objects created. 12th Computer Chapter - - Python Classes and Objects In the above program, class variable num is shared by all three objects of the class Sample.

It is initialized to zero and each time an object is created, the num is incremented by . Since, the variable shared by all objects, change made to num by one object is reflected in other objects as well. Thus the above program produces the output given below. Output The object value is = The count of object created = The object value is = The count of object created = The object value is = The count of object created = Destructor is also a special method to destroy the objects.

In Python, _ _del_ _( ) method is used as destructor. It is just opposite to constructor. class Sample: num= def (self, var): Sample.num+= self.var=var print("The object value is = ", self.var) print("The value of class variable is= ", Sample.num) def (self): Sample.num-= print("Object with value %d is exit from the scope"%self.var) S1=Sample( ) S2=Sample( ) S3=Sample( ) del S1, S2, S3 Example : Program to illustrate about the ( ) method The method gets called automatically when we deleted the object reference using the del. Note Public and Private Data Members .

The variables which are defined inside the class is public by default. These variables can be accessed anywhere in the program using dot operator. A variable prefixed with double underscore becomes private in nature. These variables can be accessed only within the class.

12th Computer Chapter - - class Sample: n1 = = def display(self): print("Class variable = ", self.n1) print("Class variable =

Related topics

Have a question about this topic?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →