问题描述
请帮助我理解这一点。我创建了一个非常简单的程序来尝试理解类。
Please help me understand this. I created a really simple program to try to understand classes.
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上调用方法不起作用?我很迷路。我看过和其他类似的Stackoverflow问题,但我不明白。非常感谢。
Why does calling the method on the class instance Polly not work? I'm pretty lost. I've looked at http://mail.python.org/pipermail/tutor/2003-May/022128.html and other Stackoverflow questions similiar to this, but I'm not getting it. Thank you so much.
推荐答案
类 Two
有一个实例方法 name()
。因此 Two.name
引用此方法,以下代码可以正常工作:
The class Two
has an instance method name()
. So Two.name
refers to this method and the following code works fine:
Polly = Two()
Two.name(Polly)
但是在 __ init __()
,通过将 name
设置为字符串来覆盖它,因此无论何时创建<$ c的新实例$ c>两个, name
属性将引用字符串而不是函数。这就是为什么以下操作失败的原因:
However in __init__()
, you override name
by setting it to a string, so any time you create a new instance of Two
, the name
attribute will refer to the string instead of the function. This is why the following fails:
Polly = Two() # Polly.name is now the string 'Polly'
Polly.name() # this is equivalent to 'Polly'()
只要确保您是为方法和实例变量使用单独的变量名。
Just make sure you are using separate variable names for your methods and your instance variables.
这篇关于Python TypeError:“ str”对象不可用于类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!