请帮助我理解这一点。我创建了一个非常简单的程序来尝试理解类。
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 问题,但我不明白。太感谢了。
最佳答案
类Two
有一个实例方法name()
。所以 Two.name
引用了这个方法,下面的代码工作正常:
Polly = Two()
Two.name(Polly)
但是在 __init__()
中,您可以通过将 name
设置为字符串来覆盖它,因此任何时候您都可以创建 Two
的新实例, name
属性将引用字符串而不是函数。这就是以下失败的原因:
Polly = Two() # Polly.name is now the string 'Polly'
Polly.name() # this is equivalent to 'Polly'()
只需确保您为方法和实例变量使用不同的变量名即可。
关于Python 类型错误 : 'str' object is not callable for class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10657022/