Object-oriented Python @property of

Acquaintance @property

Property Python is a built-in class decorator . @Property action is a method, becomes attribute to invoke .

Decorator: without changing the original function of the dynamic function to add functionality

Prior has been discussed many details of the decorator, nature is a reference to the use of Pyhton variable (pointer) characteristics and variables namespace to achieve.

def out(func):
    
    def inner(*args, **kwargs):
        
        print(f"...{args[0]} is checking...")
        return func(*args, **kwargs)
    
    return inner


@out
def check_2019_nCov(name):
    msg = f"okay, {name} is very healthy."
    return msg

ret = check_2019_nCov("youge")
print(ret)

# output
...youge is checking...
okay, youge is very health

This @property decorator, I usually use a little more on code optimization, a method, a property package in the reading experience would be better . gnaw specific implementation, did not understand, being able to apply enough.

Specific wording that method requires the use @property top decorated parameters only Self , when invoked without parentheses .

The method is decorated property @property

# 访问类的私有属性
class Foo:
    def __init__(self, score):
        self.__score = score

    @property  # 将方法装饰为属性
    def show_score(self):
        return self.__score


if __name__ == '__main__':
    s = Foo(66)
    # 在写法上更加优雅, 不用多写 "方法()" 没用的括号
    print(s.show_score)

# output:
66

Ie between members of their class play, (do not need to pass under the scenario of external parameters, showing a class member properties.), Beginning feel more Pythonic it.

A nozzle is inserted, the embodiment of the method @property decorated, is a function of the external interface to the internal properties of a view . __ Score represents private variable, can not be accessed directly, the desirable, but still accessible external internal variables feeling which can be considered Pyhton not precise enough place to go, oh no absolute security .

s = Foo(66)

# 外部直接访问私有变量(方法) 是不可以的

print(s.__score)

# output
AttributeError: 'Foo' object has no attribute '__score'

but, by the instance of the object class name __ ._ private property in such a way it is possible (construction principle why it can be studied under the direct Python class itself)

s = Foo(66)

# 没有绝对的安全哦, 只要互相尊重
print(s._Foo__score)

# output
66

@property related properties

Through the above wording, feeling nothing more than put the method into a property it seems. In addition to writing on a little more simple and elegant, what specific usage scenario is it?

Binding Properties - check - done manually

class Foo:
    def __init__(self, score):
        self.score = score
     
# 绑定score属性
s = Foo(666)

When you change the score attributes, I usually write.

s.score = 666

This very rough (directly expose the property to go) way binding properties although it is simple to write, but there is no test parameters lead can arbitrarily be changed .

Such brutal method is obviously not very reasonable. It should be a check on the score, value, type, and so can be. That we set score the property, it should be achieved two (custom) method, get_score to view value and set_score to set the value.

class Foo:
    def get_score(self):
        """获取属性值"""
        print(self.score)

    def set_score(self, value):
        """设置属性值"""
        if not isinstance(value, int):
            raise ValueError("score 必须为整数哦")
        if value > 100 or value <= 0:
            raise ValueError("score 必须在 0-100哦")

        self.score = value


if __name__ == '__main__':
    f = Foo()
    # 校验通过是可以的
    f.set_score(66)
    f.get_score()
    
    # output
    66
# 随便设置 score 属性就不可以了. 
if __name__ == '__main__':
    f = Foo()
    f.set_score('youge')
    f.get_score()
    
    # output
        raise ValueError("score 必须为整数哦")
    ValueError: score 必须为整数哦
# 继续 debug
if __name__ == '__main__':
    f = Foo()
    f.set_score('youge')
    f.get_score()
    
    # output
        raise ValueError("score 必须在 0-100哦")
ValueError: score 必须在 0-100哦

Binding Properties - check - @ property realization

  • The default is read-only
  • setter
  • deleter
class Foo:

    @property  # read only
    def score(self):
        """获取属性值"""
        return self.score

    @score.setter
    def score(self, value):
        """设置属性值"""
        if not isinstance(value, int):
            raise ValueError("score 必须为整数哦")
        if value > 100 or value <= 0:
            raise ValueError("score 必须在 0-100哦")

        # 这里一定不能 self.socre = value 哦, 不然就递归了.
        self._score = value
        print(f"set score = {value} successfully.")

if __name__ == '__main__':
    f = Foo()
    f.score = 66
    
    # print(f.score)
    # output:
    set score = 66 successfully
    
if __name__ == '__main__':
    f = Foo()
    f.score = 'youge'
    
    # output
        raise ValueError("score 必须为整数哦")
    ValueError: score 必须为整数哦

summary

  • The method @property decorator used becomes properties
  • @property default is read-only, with the setter, deleter ... and so on used together
  • Common scenario is a class instance attribute assignment is a value for checking function

Guess you like

Origin www.cnblogs.com/chenjieyouge/p/12244456.html