property

在使用私有变量的时候:

class Stu(object):
def __init__(self, name):
    self.__name = name
    
stu = Stu('xiaoming')
print(stu.__name)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
 in ()
      4 
      5 stu = Stu('xiaoming')
----> 6 print(stu.__name)

AttributeError: 'Stu' object has no attribute '__name'

那么怎么用呢?
最简单的是设置对应的函数来存取值:

class Stu(object):
    def __init__(self, name):
        self.__name = name

    def setName(self, name):
        self.__name = name
    
    def getName(self):
        return self.__name

stu = Stu('xiaoming')
print(stu.getName())
---------------------------------------------------------------------------
xiaoming

但这样可以说是相当麻烦了,使用property就可以简洁很多:

class Stu(object):
    def __init__(self, name):
        self.__name = name

    def setName(self, name):
        self.__name = name
    
    def getName(self):
        return self.__name

    name = property(getName, setName)

stu = Stu('xiaoming')
stu.name='老王'
print(stu.name)
---------------------------------------------------------------------------
老王

再进化一次:

class Stu(object):
def __init__(self, name):
    self.__name = name

    @property
    def name(self):
        return self.__name
    
    @name.setter
    def name(self, name):
        self.__name = name


stu = Stu('xiaoming')
stu.name='老张'
print(stu.name)

@property注释原get方法,函数名变为属性名
@属性名.setter注释原set方法,函数名变为属性名
函数内可以在赋值取值时执行操作

使用的时候直接使用属性名赋值取值

你可能感兴趣的:(property)