python基础--类的3种方法

类的3种方法

  • 实例方法: 需要实例化对象才能使用的方法,使用过程中可能需要截止对象的其他对象的方法完成
  • 静态方法: 不需要实例化,通过类直接访问
  • 类方法 : 不需要实例化
class Demo:
    def __init__(self, name):
        self.name = name

    @classmethod      # @classmethod装饰之后就是类方法
    def fun1(cls):    # cls代表类本身
        print(cls)
        return '-----------这是类方法-----------'

    @staticmethod     # @staticmethod装饰之后就是静态方法
    def fun2():
        return '-----------这是静态方法-----------'

    def fun3(self):   # @实例方法,self代表实例本身
        print(self)
        return '-----------这是实例方法-----------'

    @property
    def fun4(self):
        return '-----------@property定义只读属性,可以通过函数名取值-----------'




print(Demo('张三').fun1())
print(Demo.fun1())
print(Demo('张三').fun2())
print(Demo.fun2())
print(Demo('张三').fun3()) # 实例化方法需要实例化调用
print(Demo('张三').fun4)




>
<class '__main__.Demo'>
-----------这是类方法-----------
<class '__main__.Demo'>
-----------这是类方法-----------
-----------这是静态方法-----------
-----------这是静态方法-----------
<__main__.Demo object at 0x7fd2640a8310>
-----------这是实例方法-----------
-----------@property定义只读属性,可以通过函数名取值-----------

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/110493266