请帮助我理解这一点。我创建了一个非常简单的程序来尝试理解类。
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问题,但我没有理解。非常感谢。
您正在用名为
name
的方法覆盖您的name
属性。只是重命名一些东西。类
Two
有一个实例方法name()
。因此Two.name
引用此方法,以下代码工作正常:但是在
__init__()
中,您可以通过将其设置为字符串来重写name
,因此在创建Two
的新实例时,name
属性将引用字符串而不是函数。这就是以下失败的原因:只需确保为方法和实例变量使用单独的变量名。
变量和是一个名为“name”的函数。以不同的方式命名其中一个,它应该会起作用。
相关问题 更多 >
编程相关推荐