python小白求助
本帖最后由 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) print(t_1.durability)
因为你写了这个 学习中... 柿子饼同学 发表于 2021-5-11 18:25
因为你写了这个
谢谢大佬,大佬知道怎么改能让这个print输出为100吗? hiram321 发表于 2021-5-11 19:25
谢谢大佬,大佬知道怎么改能让这个print输出为100吗?
方法 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())
hiram321 发表于 2021-5-11 19:25
谢谢大佬,大佬知道怎么改能让这个print输出为100吗?
楼上说的对,把变量名改一下就好 Twilight6 发表于 2021-5-11 19:53
方法 durability() 和 这个方法内的实例变量重名
导致你调用 t_1.durability 是调用函数 durability ...
谢谢大佬
页:
[1]