理解静态方法,类方法和实例方法

class Foo(object):

    # you couldn't use self. or cls. out here, they wouldn't mean anything

    # this is a class attribute
    thing = 'athing'

    def __init__(self, bar):
        # I want other methods called on this instance of Foo
        # to have access to bar, so I create an attribute of self
        # pointing to it
        self.bar = bar

    @staticmethod
    def default_foo():
        # static methods are often used as alternate constructors,
        # since they don't need access to any part of the class
        # if the method doesn't have anything at all to do with the class
        # just use a module level function
        return Foo('baz')

    @classmethod
    def two_things(cls):
        # can access class attributes, like thing
        # but not instance attributes, like bar
        print cls.thing, cls.thing
 First, you have to understand that the choice of this name is *completely
arbitrary*. You could call it self, cls, this, bogus, helloworld or
whatsoever. The important thing is just: The first argument is (by
default) the instance.

Amongst python developers, many things aren't enforced by the language
(eg. implicit `this` referencing the instance, as in other languages) but
by conventions. It's just way more convenient to call it `self` always.
We call it `cls` when speaking about classmethods. Your method there
might have been headed by a line containing ``@classmethod``.

See http://docs.python.org/lib/built-in-funcs.html#l2h-16 for classmethod
and http://docs.python.org/tut/node11.ht...00000000000000
for this conventional stuff (paragraph "Often, the first argument ...").

你可能感兴趣的:(理解静态方法,类方法和实例方法)