Although Python's object-oriented programming principles are similar to those of other languages, it still has its own programming process and code structure, which is easy to remember.
The following describes how to calculate the Circle area and perimeter Based on the radius entered by the user:
Class_calc.py
Class cal: s = 0 # define class property r = 0 # define class property, used to receive the parameter c = 0 # define class property def _ ini _ (self, xingcan ): # The initialization method is equal to the Construction Method self. r = xingcan # assign def jsmj (self) to the class attribute: # customize the method to calculate the self. s = float (self. r) * float (self. r) * 3.14 # Call the class attribute for calculation, and change the value of the Class Attribute s def jszc (self): # Calculate the perimeter of the method self. c = 2 * float (self. r) * 3.14 # Call the class property for calculation and change the value of class property c
Main. py
From class_calc import cal # import class r = input ('Enter the radius: ') instance = cal () # create an instance (object) instance. r = r # Set the instance value for the class property. jsmj () # Call the Class Method instance. jszc () # Call the class method and modify the print ('area: ', instance. s) # Call the modified class attribute print ('Perimeter: ', instance. c) # Call the modified class attributes
Execution result: