Python TypeError:“str”对象不能为类调用

2024-06-24 21:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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问题,但我没有理解。非常感谢。


Tags: nameselfinputagerawobjectisdef
3条回答

您正在用名为name的方法覆盖您的name属性。只是重命名一些东西。

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'()

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

变量是一个名为“name”的函数。以不同的方式命名其中一个,它应该会起作用。

相关问题 更多 >