property of encapsulation

'''
BMI index (bmi is calculated, but obviously it sounds like an attribute rather than a method, it is easier to understand if we make it an attribute)

BMI values ​​for adults:
Too light: below 18.5
Normal: 18.5-23.9
Overweight: 24-27
Obesity: 28-32
very obese, above 32
  Body mass index (BMI) = weight (kg) ÷ height ^ 2 (m)
  EX:70kg÷(1.75×1.75)=22.86

'''
class People:
    def __init__(self, name,weight,height)
        self.name=name
        self.weight=weight
        self.height=height
    @property. #That    is , the decorator can disguise functional attributes as data attributes, so that the caller can call the functional attributes like calling data 
    def bmi(self):
         return self.weight/(self.height**2 )
be = People ( ' be ' , 75,1.81 )
stay.bmi = stay.weight / (stay.height * stay.height)
 print (stay.bmi)

yl=People('yangli',85,1.74)
yl.bmi=yl.weight / (yl.height * yl.height)
 print(yl.bmi)

First need to be clear. bmi is calculated, not a fixed value, which means we have to write a function, and every time the function is called,

will immediately calculate a value

be = People ('be', 75,1.81)

y1=People('yangli',85,1.74)

but obviously a person's bmi sounds more like a rank than a verb

print (egon.bmi ())

print(y1.bmi())

So we need to add a decorator to the bmi function, disguising it as a data attribute

egon.weight=70
 # print(egon.bmi) #21.604938271604937, the essence of calling egon.bmi is to trigger the execution of the function bmi, so as to get its return value 
# print(yl.bmi)


#understand _

# egon.bmi=123 # The corresponding function behind egon.bmi is a function, so it cannot be assigned 
class People:
     def  __init__ (self,name):
        self.__name=name


    @property
    def name(self): # obj.name 
        print ( ' You are accessing the username... ' )
         return self. __name

    @name.setter # obj.name='EGON' 
    def name(self,x):
         # print('==================',x) 
        if type(x) is  not str:
             raise TypeError( ' The name must be of type str, stupid ' )
        self.__name=x

    @name.deleter
    def name(self):
         # print('I won't let you delete') 
        del self .__name

obj=People('egon')

# print(obj.name)
# print(obj.name())

# print(obj.name)

# obj.name='EGON'

# print(obj.name)

# obj.name=123

del obj.name
obj.name




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324511683&siteId=291194637