首页 > 代码库 > @staticmethod和@classmethod

@staticmethod和@classmethod

# coding:utf-8class A(object):    bar = 1    def foo(self):        print hello i am foo    def myfoo(self):        print hello i am myfoo    @staticmethod    def static_foo():        print static_foo        print A.bar    @classmethod    def class_foo(aabbcc):        print class_foo        print aabbcc.bar        aabbcc().foo()A.static_foo()A.class_foo()print "~~~~~~~~~~"a = A()a.foo()a.myfoo()

static_foo
1
class_foo
1
hello i am foo
~~~~~~~~~~
hello i am foo
hello i am myfoo

 

 

参考

使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。

@staticmethod和@classmethod