Python - self, no self and cls

前端 未结 2 1535
感情败类
感情败类 2020-12-12 12:59

Yet another question on what the \'self\' is for, what happens if you don\'t use \'self\' and what\'s \'cls\' for. I \"have done my homework\", I just want to make sure I go

2条回答
  •  执笔经年
    2020-12-12 13:36

    You use self as the first argument in regular methods where the instance is passed automatically through this argument. So whatever the first argument is in a method - it points to the current instance

    When a method is decorated with @classmethod it gets the class passed as its first argument so the most common name for it is cls as it points to the class.

    You usually do not prefix any variables (hungarian notation is bad).


    Here's an example:

    class Test(object):
        def hello(self):
            print 'instance %r says hello' % self
        @classmethod
        def greet(cls):
            print 'class %r greet you' % cls
    

    Output:

    >>> Test().hello()
    instance <__main__.Test object at 0x1f19650> says hello
    
    >>> Test.greet()
    class  greet you
    

提交回复
热议问题