类/装饰器

@property装饰器负责把类中的方法转换成属性来调用
有三种调用方法

方法一:@property直接加在需要转换的方法上

class People:
    def __init__(self, name, weight, height):
        self.__name = name
        self.weight = weight
        self.height = height

    @property
    def bmi(self):
        return self.weight / (self.height ** 2)


test1 = People('nana', 50, 1.5)
print(test1.bmi)

方法二:属性名称=property(方法名1,方法名2,...)

class People:
    def __init__(self, name, weight, height):
        self.name = name
        self.weight = weight
        self.height = height

    def get_name(self):
        return self.name

    def set_name(self, val):
        if type(val) is not str:
            print('must type(str)')
            return
        self.name = val

    def del_name(self):
        print("warning:can't do it")

    name_test = property(get_name, set_name, del_name)


obj1 = People('nana', 50, 1.5)
print(obj1.name_test)
obj1.name_test = 'NANA'
print(obj1.name_test)
del obj1.name_test

方法三:首先将需要转换的方法统一成一个名称,相应的方法上添加相应的@名称推荐使用

class People:
    def __init__(self, name, weight, height):
        self.__name = name
        self.weight = weight
        self.height = height

    @property
    def namess(self):
        return self.__name

    @namess.setter
    def namess(self,val):
        if type(val) is not str:
            print('must type(str)')
            return
        self.__name=val

    @namess.deleter
    def namess(self):
        print('NO DEL')


obj2=People('simon',74,1.8)
print(obj2.namess)
obj2.namess='Tom'
print(obj2.namess)
del obj2.namess