1 classBox:#define a class named box, the class name does not have parentheses, the class contains class properties and class methods, and the class does not define class properties2 " "This is a class that calculates the volume" "#This is the __doc__ property of this class, and after executing the class, you can enter box.__doc__ in the interactive interface to view this line of explanatory text.3Openstate=04 def __init__(self):#This is the constructor of a class that automatically calls this __init__ method when the box is instantiated5self.length=0.0#This is an instance property that is accessed within the class with Self.length, outside of the class using the instance name. Length6self.width=0.07self.height=0.08Self._color='Red' 9Self.__valum=0.0#A variable at the beginning of a double-line change represents a private variable, so he is a private instance property and can only be accessed within the classTen defSet_color (self,color): OneSelf._color=Color A - defComputevalum (self):#defines a class method. -Self.__valum=self.length*self.width*Self.height the Print('length =', Self.length,'width =', Self.width,'height =', Self.height,'valum=', self.__valum) - - defInfo_color (self): - #Self.set_color (Self._color) #在类中, the way function calls functions + Print('The color of box is', Self._color) - + defOpen_box (self): A ifbox.openstate==0: at Print('Open the box.') -Box.openstate=1 - Else: - Print('The box is open and cannot be opened repeatedly.') - if __name__=='__main__': -Computa=box ()#Instantiate the box class inComputa.length=1 -computa.width=2 toComputa.height=3 + Computa.computevalum () -Computa.set_color ('Yellow') the Computa.info_color () * Computa.open_box () $ Print("')Panax Notoginseng -Computb=box ()#Instantiate the box class thecomputb.length=2 +computb.width=2 AComputb.height=3 the Computb.computevalum () +Computb.set_color ('Black') - Computb.info_color () $Computb.open_box ()
Python little exercise-function call function to make an object dynamic