# Package attributes # a healthy person can be judged by whether the value bmi class Person: def __init__(self,name,height,weight): self.name = name self.height = height self.weight = weight def bmi(self): return '{name}的bmi值为{date}'.format(name = self.name,date = round(self.weight / self.height ** 2,1)) p1 = Person('Tian',1.70,60) print(p1.bmi()) # Here bmi is a property of the concept of a noun, this call is not in line with the rules
class Person: def __init__(self,name,height,weight): self.name = name self.height = height self.weight = weight # plus the following method decorator bmi became property methods @Property DEF bmi (Self): return ' {name} bmi value of DATE} { ' .format (name = the self.name, DATE = round (self.weight / self.height ** 2,1 )) p1 = the Person ( ' Tian ' , 1.70,60 ) Print (p1.bmi) # property can be changed but here we are a disguise of property so I can not change, this python there are other decorators
class Person: def __init__(self,name,height,weight): self.name = name self.height = height self.weight = weight self.__bmi = round(self.weight / self.height ** 2, 1) @property def bmi(self): return '{name}的bmi值为{date}'.format(name = self.name,date = self.__bmi) @ bmi.setter def bmi(self,num): self.__bmi = num @bmi.deleter def bmi(self): del self.__bmi p1 = Person('Tian',1.70,60) p1.bmi = 10 Print (p1.bmi) del p1.bmi # Such modifications can, of course, is not such an approach will do no standardized calculation constructor, but here in this example
# Class methods class A: count = 20 @classmethod def cal(cls,num): return num + cls.count # Methods do not need this type of objects can be used to participate in the class method Print (A.CAL (15 )) # Parent class to get a derived class can also be a class method class B (A): count = 30 print(B.cal(15))
# Class static method class A: @staticmethod def func(user,pwd): if user == 'Tian' and pwd == 666: print('success') else: print('error') A.func ( ' Tian ' , 666 ) # Increasing the reusability of code # make the block more clean and clear