您的位置:首页 > 编程语言 > Python开发

Python——property(使一个方法看起来就像类属性一样)

2018-01-23 15:18 519 查看
"""
装饰器property:
使一个方法看起来就像类属性一样
"""

#例子1
class A:
def __init__(self,  x, y):
self.__x = x #私有变量
self.__y = y

def __add(self): #私有方法
return self.__x + self.__y

@property
def sum(self): #通过property装饰器修饰后将方法看起来就像属性一样
return self.__add()

if __name__ == '__main__':

a = A(5,6)
print(a.sum) #外部调用sum,看起来就如同属性,这个属性实际上是一个不被计算功能的方法

#例子2
class Foo:
@property
def foo(self):
return "bar"
f = Foo()
print(f.foo)

例子3
class Foo:
@property
def foo(self):
return self._foo

@foo.setter #使用foo方法的setter属性又装饰了这个foo方法,这个foo和上面的foo只是名字相同,实际是不同的
def foo(self, value):
self._foo = value
f = Foo()
f.foo = 100
print(f.foo)
#一定要注意了,由property装饰器装饰后的函数返回的是一个对象

#例子4
class Silly:
@property
def silly(self):
print("You are getting silly")
return self._silly #返回的是一个property对象
@silly.setter
def silly(self, value):
print("You are making silly {}".format(value))
self._silly = value

@silly.deleter #删除函数(目前我也不知道这么去使用它)
def silly(self):
print("Whoah you killed silly!")
del self._silly
s = Silly
s.silly = 100
print(s.silly)

#再看最后的一个例子,一个苹果类中的价格属性
class Apple:
def __init__(self, price):
self.price = price
a = Apple(19)
print(a.price)
a.price = 20 #随意被更改了,存在数据安全问题
print(a.price)

#改进代码v1.0
class Apple:
def __init__(self, price):
self._price = price #将属性增加单下划线,变成半保护
a = Apple(19) #初始化价格
print(a._price)  #打印
a.price = 25 #尝试的修改
print(a._price) #貌似没有修改成功,还是原来的19

#继续改进 v1.0.1
class Apple:
def __init__(self, price):
self._price = price
a = Apple("hello") #price是价格,但被人传入的是字符串,也就是说被随意传入不同的数据类型的数据,需要继续改进
print(a._price)

#继续改进 v1.0.2
class Apple(object):
def get_price(self):
return self.__price

def set_score(self, price):
if not isinstance(price, int):
raise ValueError('Price must be an integer!')
self.__price = price

a = Apple()
a.set_score(19) #那么可以再试试传入字符串,那么则会引发异常
print(a.get_price())

#最终版本 v2.0
class Apple(object):
@property
def get_price(self):
try:
return self.__price
except AttributeError:
print("No Data...")

@get_price.setter #@property本身又创建了另一个装饰器@get_price.setter,负责把一个setter方法变成属性赋值
def set_score(self, price):
if not isinstance(price, int):
raise ValueError('Price must be an integer!')
self.__price = price

a = Apple()
a.set_score = 20
print(a.get_price)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python property
相关文章推荐