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()

另外,覆盖与继承上述几种都是一样的.....

猜你喜欢

转载自blog.csdn.net/qq_37312720/article/details/83050580
今日推荐