马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 hiram321 于 2021-5-11 18:07 编辑
哪位大佬知道为什么在用(.durability)时得到<bound method Train.durability of <__main__.Train object at 0x00000220629F6C40>>class Train:
T = 100
def __init__(self, model, age, origin, speed):
self.model = model
self.age = age
self.origin = origin
self.speed = speed
def durability(self):
self.durability = self.T
return self.durability
def birthday(self):
self.age +=1
self.T -=10
if self.T <= 0:
print(f"{self.model} is no longer in operation.")
else:
return self.T
def repair(self):
self.T +=10
if self.T >= 100:
print(f"{self.model} is good as nwe!")
else:
return self.T
t_1 = Train('Waratah', 3, 'Sydney', 60)
print("{}, age {}.".format(t_1.model, t_1.age))
print(t_1.durability)
t_1.birthday()
print("{}, age {}.".format(t_1.model, t_1.age))
t_1.repair()
print(t_1.durability)
方法 durability() 和 这个方法内的实例变量重名
导致你调用 t_1.durability 是调用函数 durability 而不是实例变量 durability
变量名改改就行,参考代码:
class Train:
T = 100
def __init__(self, model, age, origin, speed):
self.model = model
self.age = age
self.origin = origin
self.speed = speed
def durability(self):
self.durability_ = self.T
return self.durability_
def birthday(self):
self.age +=1
self.T -=10
if self.T <= 0:
print(f"{self.model} is no longer in operation.")
else:
return self.T
def repair(self):
self.T +=10
if self.T >= 100:
print(f"{self.model} is good as nwe!")
else:
return self.T
t_1 = Train('Waratah', 3, 'Sydney', 60)
print("{}, age {}.".format(t_1.model, t_1.age))
print(t_1.durability())
t_1.birthday()
print("{}, age {}.".format(t_1.model, t_1.age))
t_1.repair()
print(t_1.durability())
|