Self is an instance of a class
Self is a bit like this in Java and has no practical meaning. But it is customary to use self to represent an instance of a class
class " Span style= "COLOR: #000000" > A: def func ( Self): print (self) #
print (Self.__class__ ) # points to the class a = A () A.func () # <__main__. A object at 0x02c40f10> # <class "__ main__. A '; # a=a () A.func () procedure is equivalent to a.func (a)
Self represents an instance of a class, not a class.
could self be omitted?
Look at the code first, the performance
class B: def func (): Print ("ok! " = B () b.func ()#typeerror:func () takes 0 positional arguments but 1 was given
Error, the reason is very simple. The B=b () B.func () procedure is equivalent to B.fun (b), and func () is not required in class B, so a parameter B is passed and an error is made.
If you want to succeed, you need to implement:
>>>b.func ()
Self in the inheritance
classParent ():defp (self):Print(self)classChild (Parent):defC (self):Print(self) C=Child () c.c () C.P () p=Parent () p.p ()#<__main__. Child object at 0x02ce6270>#<__main__. Child object at 0x02ce6270>#<__main__. Parent object at 0x02ce6c90>
Running C.P () is equivalent to CHILD.P (c), so self refers to an instance of the child class
in a descriptor class, self refers to an instance of a descriptor class
classDesc:def __get__(self, INS, CLS):Print('Self in Desc:%s'%Self )Print(self, INS, CLS)classtest:x=Desc ()defprt (self):Print('Self in Test:%s'%Self ) T=Test () t.prt () T.xSelf in Test: <__main__. Test object at 0x0000000002a570b8>self in Desc: <__main__. Desc object at 0x000000000283e208><__main__. Desc object at 0x000000000283e208> <__main__. Test object at 0x0000000002a570b8> <class ' __main__. Test ' >
The call here is T.x, which is the property x of the instance T of the test class, because the attribute x is not defined in the instance T, so the class attribute x is found, and the property is a descriptor property, an instance of the Desc class, so there is no method for test.
Resources:
http://python.jobbole.com/81921/
Understanding of Python Foundation ===self