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

后端 未结 6 2062
伪装坚强ぢ
伪装坚强ぢ 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:42

    self is just a name, your self in this case is a class variable and not this for the object using which it is called,

    self is treated as a normal variable and it is not defined, where as the self in the function comes from the object used for calling.

    you want to treat the object reference in self as a class variable which is not possible.

提交回复
热议问题