Python的類方法、靜態方法和例項化方法
阿新 • • 發佈:2019-02-17
#-*- coding:utf-8 -*-
class A:
def __init__(self,name):
self.name=name
@staticmethod
def staticfun():
print("this is static function")
@classmethod
def classfun(cls):
print("this is class function")
def entityfun(self):
print("this is a entity function" )
AA=A("AA")
AA.staticfun()
A.staticfun()
A.classfun()
AA.classfun()
AA.entityfun()
#會報錯,只能用例項化物件來呼叫
A.entityfun()
實驗結果:
/usr/bin/python3.5 /home/liusenubuntu/PycharmProjects/sentence/pythonlearn/staticfunction.py
this is static function
this is static function
this is class function
this is class function
this is a entity function
Traceback (most recent call last):
File "/home/liusenubuntu/PycharmProjects/sentence/pythonlearn/staticfunction.py", line 19, in <module>
A.entityfun()
TypeError: entityfun() missing 1 required positional argument: 'self'
Process finished with exit code 1
其中cls是類變數,self是例項化物件,例項化方法只能用例項化物件呼叫,也可以傳入例項化物件引數。