我正在学习python中的封装和抽象,我遇到了属性函数和装饰器。常见的例子是这样的情况。
class Celsius():
def __init__(self, temperature = 0):
self.set_temperature(temperature)
def to_fahrenheit(self):
return (self._temperature * 1.8) + 32
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature,set_temperature)我不明白为什么属性函数要将描述符分配给temperature而不是self.temperature。为实例而不是类创建getter或setter功能不是一种支持吗?
就像这样
self.temperature = property(get_temperature,set_temperature)使用
test = Celsius()
pprint(test.__dict__)返回实例对象只具有self._temperature属性(我们试图将其设置为私有)。使用pprint(Celsius.__dict__)返回的实际上是我们在使用对象时访问的具有温度属性的类,据我理解,这是没有意义的,因为我感兴趣的是为实例创建功能和访问实例属性,而不是类属性。
(预先谢谢:)
发布于 2022-03-07 18:11:56
在这个方法之外没有自我。这是定义一个类属性。
@Barmar在上面有一个有用的评论。
常用的类函数参数self和cls在类函数之外不可用。在本例中,您定义的是类的静态成员。默认情况下,以这种方式定义的vars (如您的temperature =)是类的静态成员。
在这里看到一些关于静态成员的有用提示:Python中可以使用静态类变量吗?
但为什么语法是那样的。不应该将属性赋值给实例变量吗?
注意下面的内容。class_static_var = 4的行为类似于人们看待cls.class_static_var = 4的方式,但它与self.instance_var = 4并不相似。要定义实例var,可以使用__init__方法
class DemoClass:
def __init__(self):
self.instance_var = 3
class_static_var = 4https://stackoverflow.com/questions/71385386
复制相似问题