class Animal: def __init__(self, animal): self.animal = animal def type(self, type=self.animal): print type
运行的时候出现 NameError: name 'self' is not defined?
天蓬老师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)
巴扎黑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?