请帮助我理解这一点。我创建了一个非常简单的程序来尝试理解类。
class One(object):
def __init__(self, class2):
self.name = 'Amy'
self.age = 21
self.class2 = class2
def greeting(self):
self.name = raw_input("What is your name?: ")
print 'hi %s' % self.name
def birthday(self):
self.age = int(raw_input("What is your age?: "))
print self.age
def buy(self):
print 'You buy ', self.class2.name
class Two(object):
def __init__(self):
self.name = 'Polly'
self.gender = 'female'
def name(self):
self.gender = raw_input("Is she male or female? ")
if self.gender == 'male'.lower():
self.gender = 'male'
else:
self.gender = 'female'
self.name = raw_input("What do you want to name her? ")
print "Her gender is %s and her name is %s" % (self.gender, self.name)
Polly = Two()
Amy = One(Polly)
# I want it to print
Amy.greeting()
Amy.buy()
Amy.birthday()
问题代码
Polly.name() # TypeError: 'str' object is not callable
Two.name(Polly)# Works. Why?
为什么调用类实例 Polly 上的方法不起作用?我很迷茫。我查看了http://mail.python.org/pipermail/tutor/2003-May/022128.html和其他与此类似的 Stackoverflow 问题,但我不明白。非常感谢。