1. 程式人生 > >python function和method staticfunction和classmethod

python function和method staticfunction和classmethod

用pycharm敲打碼的時候,ide會自動補全其型別,p,m,c,v,f代表什麼意思

p:parameter 引數 m:method 方法 c:class 類 v:variable 變數 f:function 函式

function and method function(函式) —— A series of statements which returns some value toa caller. It can also be passed zero or more arguments which may beused in the execution of the body. method(方法

) —— A function which is defined inside a class body. Ifcalled as an attribute of an instance of that class, the methodwill get the instance object as its first argument (which isusually called self).

函式就是不在class裡的,只能import使用,method在類裡面,需要將類例項化使用,或者直接給類引數使用

staticmethod and classmethod

class A(object):
#正常的例項方法
    def foo(self, x):
        print("executing foo(%s,%s)" % (self, x))
        print('self:', self)
#與上述一致,只不過傳的引數不是self,但是都是傳遞當前的類物件,呼叫的時候可以直接類名A.foo
    @classmethod
    def class_foo(cls, x):
        print("executing class_foo(%s,%s)" % (cls, x))
        print('cls:', cls)
#這個上述兩種呼叫都可以,有點像Java的static
    @staticmethod 
    def static_foo(x):
        print("executing static_foo(%s)" % x)    
a = A()

另外,覆蓋與繼承上述幾種都是一樣的.....