请帮我理解这个.我创建了一个非常简单的程序来尝试理解类.
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()
Run Code Online (Sandbox Code Playgroud)
问题代码
Polly.name() # TypeError: 'str' object is not callable
Two.name(Polly)# Works. Why?
Run Code Online (Sandbox Code Playgroud)
为什么调用类实例Polly上的方法不起作用?我很丢失.我看过http://mail.python.org/pipermail/tutor/2003-May/022128.html和其他与此类似的Stackoverflow问题,但我没有得到它.非常感谢.
该类Two
有一个实例方法name()
。所以Two.name
参考这个方法,下面的代码工作正常:
Polly = Two()
Two.name(Polly)
Run Code Online (Sandbox Code Playgroud)
然而__init__()
,在 中,您可以name
通过将其设置为字符串来进行覆盖,因此每当您创建 的新实例时Two
,该name
属性都将引用该字符串而不是函数。这就是以下失败的原因:
Polly = Two() # Polly.name is now the string 'Polly'
Polly.name() # this is equivalent to 'Polly'()
Run Code Online (Sandbox Code Playgroud)
只需确保您的方法和实例变量使用单独的变量名称即可。