search

Home  >  Q&A  >  body text

python类出错 NameError: name 'self' is not defined

class Animal:
    def __init__(self, animal):
        self.animal = animal

    def type(self, type=self.animal):
        print type

运行的时候出现 NameError: name 'self' is not defined?

ringa_leeringa_lee2824 days ago1055

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 11:13:27

    The default value of the method parameter is initialized when the function is defined, and self refers to the instantiated class of the class. It only has a value after instantiation, so there is a compilation error here (not a runtime error)

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:13:27

    If the default value of printing must be set to self.animal, try this:

     class Animal(object):
         def __init__(self,animal):
             self.animal = animal
         def type(self,type=None):
             print type if type else self.animal

    You also need to know about self. Where can you access self in a class and where can’t you access it?

    reply
    0
  • Cancelreply