Python TypeError: 'str' object cannot be called for class

Please help me figure this out. 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() 

PROBLEM CODE

 Polly.name() # TypeError: 'str' object is not callable Two.name(Polly)# Works. Why? 

Why doesn't calling a method on an instance of the Polly class work? I'm pretty lost. I looked at http://mail.python.org/pipermail/tutor/2003-May/022128.html and other similar Stackoverflow questions similar to this, but I don't understand. Thank you very much.

+6
source share
4 answers

Two class has an instance method name() . Thus, Two.name refers to this method, and the following code works fine:

 Polly = Two() Two.name(Polly) 

However, in __init__() you override name by setting it to a string, so anytime you create a new instance of Two , the name attribute will refer to the string instead of the function. Here's why the following:

 Polly = Two() # Polly.name is now the string 'Polly' Polly.name() # this is equivalent to 'Polly'() 

Just make sure you use separate variable names for your methods and your instance variables.

+3
source

You rewrite your name attribute with the name method. Just rename something.

+3
source

You have both a variable and a function called "name" in "Two." Name one of them differently, and it should work.

+1
source

I would strongly suggest that you get used to thoroughly naming things. As you can see, even with very small pieces of code, you may run into problems. You will definitely want to read the PEP style of PEP very carefully. http://www.python.org/dev/peps/pep-0008/

+1
source

Source: https://habr.com/ru/post/916114/


All Articles