Property and private property --Python3

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Properties: The transformation method
when writing property code: above methods plus @property, only one parameter method self.
Call attributes: no parentheses, using the object method.
Scenario properties: For simple method, when no parameter passing and return a value, may be used.

class Foo:
    def __init__(self):
        pass

    @property
    def start(self):
        return 'start'

    @property
    def stop(self):
        return 'stop'
        
f_obj = Foo()
print(f_obj.start, f_obj.stop)
'''
start stop
'''

Of course, there are public and private property points, define the private property can be added in front of the method of double underline _ _. Private attributes accessible through the use of other methods in class:

class Foo:
    def __init__(self):
        pass
	# 私有属性__start
    @property
    def __start(self):
        return 'start!'
        
	# 私有属性__stop
    @property
    def __stop(self):
        return 'stop!'
        
	# 通过方法访问私有属性
    def get_start_stop(self):
        print(self.__start)
        print(self.__stop)
        
f_obj = Foo()
f_obj.get_start_stop()
'''
start!
stop!
'''

Guess you like

Origin blog.csdn.net/Thanlon/article/details/94229392