@property
通过property装饰器将类方法进行装饰,这样调用类方法时,看起来就像是直接调用了属性来得到值,调用方法时方法不用加()
class person:
def __init__(self, age):
self.__age = age
@property
def age_property(self):
return self.__age + "...."
@age_property.setter
def age_property(self, newage):
self.__age = newage
p = person("年龄23")
print(p.age_property)
p.age_property = "年龄18"
print(p.age_property)
# property应用实例
class Goods(object):
dicount = 0.5
def __init__(self, name, price):
self.name = name
self.__price = price
@property
def price(self):
return self.__price * Goods.dicount
apple = Goods('苹果', 5)
print(apple.price) # 直接通过实例访问属性,从而来调用方法
删除类的属性和修改类的属性
class person:
def __init__(self, name):
self.__name = name
@property
def name_property(self):
return self.__name
@name_property.deleter
def name_property(self):
del self.__name
@name_property.setter
def name_property(self, newname):
self.__name = newname
p1 = person("jack")
print("修改前的属性值:", p1.name_property) # 直接通过实例访问属性,从而来调用方法
# 修改类的属性
p1.name_property = "janme"
print("修改后的属性值:", p1.name_property)
# 删除类的属性
del p1.name_property
# print(p1.name_property)
# 检查Python是否是Python3
import torch
print(torch._six.PY3)
输出:
年龄23....
年龄18....
2.5
修改前的属性值: jack
修改后的属性值: janme
True