Package Concept:
Property Code 1
ImportMathclassCircle:def __init__(Self,radius):#radius of the circleself.radius=radius @property#add Adorner, Area=property (area) defArea (self):returnMath.PI * self.radius**2#Calculate Area@property#add Adorner, Perimeter=property (perimeter) defperimeter (self):return2*math.pi*self.radius#Calculate PerimeterC=circle (7) C.radius=10Print(C.radius)#Print the radius of a circle#print (C.area ()) #会报错, TypeError: ' Float ' object is not callable, as: Float objects are not callable#print (C.perimeter ()) #float对象是不可调用的Print(C.area)#The surface is a data property, but this is essentially a function attribute that invokes the area function above and prints the circlePrint(C.perimeter)#print the perimeter of a circle
Code Snippet 1
Property Code 2
classpeople:def __init__(self,name,age,height,weight): Self.name=name Self.age=Age Self.height=Height Self.weight=Weight @property#the adorner can be understood as Bodyindex=property (Bodyindex) defBodyindex (self):#Calculate body Fat returnself.weight/(self.height**2) P1=people ('Cobila', 18,1.65,75)Print(P1.bodyindex)#too light: less than 18.5, normal: 18.5-23.9, overweight: 24-27, obese: 28-32, very obese, higher thanp1.weight=200Print(P1.bodyindex)Code Snippet 2
Property Code 3
classpeople:def __init__(self,name): Self.__name=name#Self.__name #def tell_name (self): #return Self.__name@propertydefname (self):returnSelf.__nameP1=people ('Cobila')#print (P1.tell_name ())Print(P1.name)#trigger the name () function to run#p1.name= ' Egon ' #会报错, Attributeerror:can ' t set attributeCode Snippet 3
Property Code 4
classpeople:def __init__(self,name,sex): Self.name=name self.__sex=sex#self.sex= ' male ' p1.sex (equivalent to self.sex) = ' Male '@property#Check defSex (self):returnSelf.__sex #P1.__sex@sex. Setter#Modify defSex (self,value):#Gender is a string type #print (self,value) # if notIsinstance (VALUE,STR):#python has no type restrictions, so you can only add this type limit yourself RaiseTypeError ("gender must be a string type") self.__sex=value#p1.__sex= ' Male '@sex. deleter#Delete defSex (self):delSelf.__sex #trigger the Delete function to run, del P1.__sex #del self.sex #这是错误的#p1=people (' Cobila ', ' Male ')#print (p1.sex)#p1.sex= ' 123 '#p1.sex = ' female ' #这个等式触发def sex (self,value), pass female this value to value#print (p1.sex) #输出female#p1.sex=9999999 #由于更改的不是字符串类型, so it throws an exception#p1=people (' Cobila ', 9999999999999999) #这里更改的是def sex (self): Self.__sex belowP1=people ('Cobila','male')#instantiate a trigger __init__ runPrint(P1.sex)#Output Male#del p1.sex # @sex. deleter one executes it (Def sex (self)), Del Self.sex, infinite recursion, always deletes itself, will error (recursionerror:maximum recursion depth Exceeded)#print (p1.sex)Code Snippet 4
Python-based encapsulation