Python TypeError: 'str' object is not callable for class

后端 未结 4 497
情话喂你
情话喂你 2021-01-12 11:14

Please help me understand this. I created a really simple program to try to understand classes.

class One(object):
    def __init__(self, class2):
        s         


        
相关标签:
4条回答
  • 2021-01-12 11:42

    You are overwriting your name attribute with method called name. Just rename something.

    0 讨论(0)
  • 2021-01-12 11:51

    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)
    

    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.

    0 讨论(0)
  • 2021-01-12 11:52

    I would strongly suggest you get into the habit of carefully naming things. As you can see, even with very small pieces of code, you can get into trouble. You'll definitely want to read the Python style PEP very carefully. http://www.python.org/dev/peps/pep-0008/

    0 讨论(0)
  • 2021-01-12 11:59

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

    0 讨论(0)
提交回复
热议问题