静态方法@staticmethod
- 静态方法和函数的区别是:
静态方法
定义在类这个空间(类命名空间)中,而函数
则定义在程序所在的空间(全局命名空间)中。 - 静态方法没有类似
self、cls
这样的特殊参数,因此 Python 解释器不会对它包含的参数做任何类或对象的绑定。也正因为如此,类的静态方法中无法调用任何类属性和类实例方法。
- 静态方法创建 :使用
staticmethod()
或者@staticmethod
类方法@classmethod
- 类方法第一个参数约定名为
cls
,类本身会绑定给 cls 参数 - 类方法可以访问类属性,对类属性进行的处理是
有记忆性的
类实例方法
- 类实例方法第一个参数约定名为
self
,用于绑定调用此方法的实例对象,可以通过self
访问实例属性。 - 通常情况下,在类中定义的方法默认都是实例方法
cls 和 self 参数一样,命名不是规定的(可以随意命名),只是约定俗称的习惯而已。
方法之间的调用
方法
class Test:
@staticmethod
def a():
print('aaa')
@staticmethod
def b():
print('bbb')
Test.a()
Test.c()
@classmethod
def c(cls):
print('ccc')
@classmethod
def d(cls):
print('ddd')
Test.a()
cls.a()
Test.b()
cls.b()
def e(self):
print('eee')
def f(self):
print('fff')
self.a()
self.c()
self.e()
调用
test = Test()
print('----------------')
test.a() # Test.a() 实例对象和类对象都可以调用
print('---------------a')
test.b() # Test.b() 实例对象和类对象都可以调用
print('---------------b')
test.c() # Test.c() 实例对象和类对象都可以调用
print('---------------c')
test.d() # Test.d() 实例对象和类对象都可以调用
print('---------------d')
test.e() # 只能实例对象调用
print('---------------e')
test.f() # 只能实例对象调用
print('---------------f')
输出
"""
----------------
aaa
---------------a
bbb
aaa
ccc
---------------b
ccc
---------------c
ddd
aaa
aaa
bbb
aaa
ccc
bbb
aaa
ccc
---------------d
eee
---------------e
fff
aaa
ccc
eee
---------------f
"""
相关文章