侧边栏壁纸
博主头像
cn2linux博主等级

行动起来,活在当下

  • 累计撰写 128 篇文章
  • 累计创建 1 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

草稿:Python 类、静态、实例方法说明

创建一个测试类

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()
('class method called', <class MyClass at 0x101a2f4c8>)
obj.staticmethod()
'static method called'

不实例化类直接调用类下的所有方法

# Calling instance methods fails
# if we only have the class object:
>>> MyClass.classmethod()
('class method called', <class MyClass at 0x101a2f4c8>)
>>> MyClass.staticmethod()
'static method called'
>>> MyClass.method()
TypeError: 
    "unbound method method() must be called with MyClass "
    "instance as first argument (got nothing instead)"

0

评论区