欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

马哥 今日小技巧 类方法和静态方法 实例方法差异 有大用

# @classmethod vs @staticmethod vs "plain" methods

# What's the difference?


class MyClass:

    def method(self):

        """

        Instance methods need a class instance and

        can access the instance through `self`.

        """

        return 'instance method called', self


    @classmethod

    def classmethod(cls):

        """

        Class methods don't need a class instance.

        They can't access the instance (self) but

        they have access to the class itself via `cls`.

        """

        return 'class method called', cls


    @staticmethod

    def staticmethod():

        """

        Static methods don't have access to `cls` or `self`.

        They work like regular functions but belong to

        the class's namespace.

        """

        return 'static method called'


# All methods types can be

# called on a class instance:

>>> obj = MyClass()

>>> obj.method()

('instance method called', <MyClass instance at 0x1019381b8>)

>>> obj.classmethod()


普通分类: