|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
问题在print(t.fah())当我这么写的时候报错:TypeError: 'float' object is not callable 我把get魔法方法返回值转成浮点型也没用。
def __get__(self, instance, owner):
return float(self.value)
print(t.fah)这样写是正确的,是什么原因导致加了()报错的?
到底什么情况要加()什么情况下不用加?
class Celsius:
def __init__(self,value=12.2):
self.value = float(value)
def __set__(self, instance, value):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
class Fahrenheit:
def __get__(self, instance, owner):
return instance.cel * 1.8 +32
def __set__(self, instance, value):
instance.cel = (float(value)-32) /1.8
class Temperature:
cel = Celsius()
fah = Fahrenheit()
t = Temperature()
t.cel= 22
print(t.fah)
class Temperature:
cel = Celsius()
fah = Fahrenheit()
把上面红色部分替换成具体数字,容易理解
class Temperature:
cel = 22
fah = 12.2
现在可以看出,你实际上是在类里面写了两个类属性,cel ,fah ,只不过这个类属性的值是一个 类的实例
类属性,和实例属性,实际上都是能用 . 调用的
t = Temperature()
print(t.fah)
就像这样
|
|