print(num," is Even number") else: print(num," is Odd number") n= () x = int(input("Enter a value: ")) n.check(x) When you execute this program, Python accepts the value entered by the user and passes it to the method check through object. Output Enter a value: is Even number Output Enter a value: is Odd number Example : program to check and print if the given number is odd or even using class Constructor and Destructor in Python . Constructor is the special function that is automatically executed when an object of a class is created. In Python, there is a special function called “init” which act as a Constructor.
It must begin and end with double underscore. This function will act as an ordinary function; but only difference is, it is executed automatically when the object is created. This constructor function can be defined with or without arguments. This method is used to initialize the class variables.
General format of _ _init_ _ method (Constructor function) def _ _init_ _(self, [args ……..]): <statements> 12th Computer Chapter - - class name class Sample: Parameter def (self, num): print("Constructor of class Sample...") self.num=num Instance variable print("The value is :", num) S=Sample( ) Example : Program to illustrate Constructor The above class “Sample”, has only a constructor with one parameter named as num. When the constructor gets executed, first the print statement, prints the “Constructor of class Sample….”, then, the passing value to the constructor is assigned to instance variable self.num = num and finally it prints the value passed along with the given string. The above constructor gets executed automatically, when an object S is created with actual parameter . Thus, the Python display the following output.
Constructor of class Sample... The value is : Class variable defined within constructor keep count of number of objects created with the class. Instance variables are the variables whose value varies from object to object. For every object, a separate copy of the instance variable will be created.
Instance variables are declared inside a method using the