Why does “self” outside a function's parameters give a “not defined” error?

后端 未结 6 2072
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 13:05

Look at this code:

class MyClass():

    # Why does this give me \"NameError: name \'self\' is not defined\":
    mySelf = self

    # But this does not?
            


        
6条回答
  •  长发绾君心
    2021-01-20 13:35

    Because the name self is explicitly defined as part of the arguments to myFunction. The first argument to a method is the instance that the method was called on; in the class body, there isn't an "instance we're dealing with", because the class body deals with every possible instance of the class (including ones that don't necessarily exist yet) - so, there isn't a particular object that could be called self.

    If you want to refer to the class itself, rather than some instance of it, this is spelled self.__class__ (or, for new-style classes in Py2 and all classes in Py3, type(self)) anywhere self exists. If you want to be able to deal with this in situations where self doesn't exist, then you may want to look at class methods which aren't associated with any particular instance, and so take the class itself in place of self. If you really need to do this in the class body (and, you probably don't), you'll just have to call it by name.

提交回复
热议问题