我是 Python 初学者。为什么这段代码不打印 100?
class Pet(object):
def __init__(self):
self.name = ''
self.age = 0
def getName(self, newname):
self.name = newname
return self.name
def getAge(self, aging):
self.age += aging
return self.age
polly = Pet()
polly.getAge(100)
print polly.getAge
请您参考如下方法:
通过它。
polly = Pet() # initialize a new Pet
polly.getAge(100) # add 100 to polly.age
print polly.getAge # print the getAge method bound to polly
你是不是想做
polly = Pet()
polly.getAge(100)
print polly.age
或者:
polly = Pet()
print polly.getAge(100)
?
无论如何,您应该保持友善,不要使用 getX 方法改变值。这绝对是意想不到的行为。
