python__高级 : Property 的使用

此页面是否是列表页或首页?未找到合适正文内容。

python__高级 : Property 的使用

标签:elfspan私有属性selfstylesetter创建使用return

一个类中,假如一个私有属性,有两个方法,一个是getNum , 一个是setNum 它,那么可以用 Property 来使这两个方法结合一下,比如这样用 num = property(getNum, setNum)

那么 如果创建一个对象 t = Test() , t.num 这样就相当于调用了 getNum 方法, t.num = 100 这样就相当于调用了 setNum 方法 ,例如:

class Test(object):
def __init__(self):
self.__num = 0
 
def getNum(self):
print(‘—-get—-‘)
return self.__num

def setNum(self, newNum):
print(‘—-set—-‘)
self.__num = newNum

num = property(getNum, setNum)

t = Test()
t.num = 100
print(t.num)

>>>—-set—-
—-get—-
100

当然,一般在使用property的时候,都会用装饰器的方法使用它,因为这样看起来更加简单:

class Test(object):
def __init__(self):
self.__num = 0

@property
def num(self):
print(‘—-get—-‘)
return self.__num

@num.setter # 两个方法名要相同,用 方法名.setter 声明设置它的方法.
def num(self, newNum):
print(‘—-set—-‘)
self.__num = newNum

t = Test()
t.num = 100
print(t.num)

>>>—-set—-
—-get—-
100

这样上面两个方法就可以用相同的名字,而编译器会在 t.num 这种取值操作的时候调用 用 @property 装饰的方法 , 在 t.num=100 这种赋值操作的时候调用 用 @num.setter 装饰的方法.

这样的作用就相当于把方法进行了封装,以后使用起来会更加方便.

python__高级 : Property 的使用

标签:elfspan私有属性selfstylesetter创建使用return

原文地址:https://www.cnblogs.com/cccy0/p/9057467.html

作者: liuzhihao

为您推荐

返回顶部