class Animal: def __init__(self, animal): self.animal = animal def type(self, type=self.animal): print type
运行的时候出现 NameError: name 'self' is not defined?
NameError: name 'self' is not defined?
ringa_lee
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?
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:
You also need to know about self. Where can you access self in a class and where can’t you access it?