Chapter VII of object-oriented (9): Let's do like a function attribute data attributes - use property decorator

Use 7.12 property decorator

Meaning: This section describes the decorator allows us to function as a data property attributes do!

  • Here we present the following decorators:
    • @property
    • @func.setter
    • @func.deleter

Scene: When a data attribute required by calculation or processing time to come, we need to calculate the function attributes, so call when the user needs to call the method to get this property. But for users, the work function property is used instead to obtain the data attributes. This situation how can we do it?

At this time, we can increase a @property decorator on the property to achieve this function → function attribute data attributes camouflage

@property decorator:

# BMI 体质指数计算例: bmi = 体重 / 身高的平方

class People:
    def __init__(self, name, weight, height):
        self.name = name
        self.weight = weight
        self.height = height
        
    @property  # 装饰器修饰bmi函数属性
    def bmi(self):  # 因为bmi只是一个对象的属性而不是对象的动作,我们不想用方法来调用。
        return self.weight / (self.height ** 2)  # 返回结果

p1 = People('a', 85, 1.78)

print(p1.bmi)  # 如果没有@property装饰器,我们这里需要用p.bmi()来调用。

# 注意:bmi是个方法,所以不能直接赋值
# p.bmi = 3333  # 这个会报错:AttributeError。不过真想对这个方法进行修改,可以用setter,deleter装饰器重写该方法

@ Func.setter, @ func.deleter decorator:

class People:
    def __init__(self, name):
        self.__name = name
        
    @property  
    def name(self):
        return self.__name
    
    @name.setter  # 设定用装饰器
    def name(self, val):
        if not isinstance(val, str):
            print('名字必须是字符')
            return
        self.__name = val
        
    @name.deleter
    def name(self):
        print('deleter')
        del self.__name  # 删除name属性
        
p1 = People('a')

print(p1.name)

p1.name = 'A'  # 可以(似乎只能)用 = 来赋值,@setter
print(p1.name)

p1.name = 123  # 不符合类型会print

print(p1.__dict__)
del p1.name  # 可以用del来删除, @deleter
print(p1.__dict__)

Results of the:

a
A
名字必须是字符
{'_People__name': 'A'}
deleter
{}

Guess you like

Origin www.cnblogs.com/py-xiaoqiang/p/11210452.html