请帮助我理解这一点。我创建了一个非常简单的程序来尝试理解类。

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引用了这种方法,下面的代码可以很好地工作:

Polly = Two()
Two.name(Polly)

但是在name()中,您通过将其设置为字符串来覆盖Two.name,因此每当您创建__init__()的新实例时,name属性将引用字符串而不是函数。这就是以下失败的原因:
Polly = Two()      # Polly.name is now the string 'Polly'
Polly.name()       # this is equivalent to 'Polly'()

只需确保您的方法和实例变量使用单独的变量名。

关于python - Python TypeError:'str'对象不能为类调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10657022/

10-11 03:45
查看更多