python类出错 NameError: name 'self' is not defined
ringa_lee
ringa_lee 2017-04-17 11:11:27
0
2
1057
class Animal:
    def __init__(self, animal):
        self.animal = animal

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

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

ringa_lee
ringa_lee

ringa_lee

reply all(2)
Peter_Zhu

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)

巴扎黑

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template