类的3种方法
- 实例方法: 需要实例化对象才能使用的方法,使用过程中可能需要截止对象的其他对象的方法完成
- 静态方法: 不需要实例化,通过类直接访问
- 类方法 : 不需要实例化
class Demo:
def __init__(self, name):
self.name = name
@classmethod
def fun1(cls):
print(cls)
return '-----------这是类方法-----------'
@staticmethod
def fun2():
return '-----------这是静态方法-----------'
def fun3(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定义只读属性,可以通过函数名取值-----------