类的属性和方法

一、类的静态方法和类方法

>>> class TestStaticMethod():
  # 静态方法是需要传入任何参数的
def foo(): print('calling static method foo()')
  foo
= staticmethod(foo) >>> class TestClassMethod():
  # 类方法需要指定一个变量,作为调用时传入给类方法的第一个参数,一般都使用cls来指定
def foo(cls): print('calling class method foo()') print('foo() is part of class:',cls.__name__) foo = classmethod(foo) >>> tsm = TestStaticMethod()
# 可以通过类名加方法的方式调用
>>> TestStaticMethod.foo() calling static method foo()
# 通过类的实例来调用静态方法
>>> tsm.foo() calling static method foo() >>> tcm = TestClassMethod()
# 通过类的实例调用类方法
>>> tcm.foo() calling class method foo() foo() is part of class: TestClassMethod
# 通过类调用类方法
>>> TestClassMethod.foo() calling class method foo() foo() is part of class: TestClassMethod

 对上面的代码使用装饰器来优化:

# 使用装饰器对函数重新绑定和赋值
>>> class TestStaticMethod():
  # 静态方法是需要传入任何参数的,使用装饰器调用,相当于:foo = staticmethod(foo)
    @staticmethod
    def foo():
        print('calling static method foo()') 
>>> class TestClassMethod():
  # 类方法需要指定一个变量,作为调用时传入给类方法的第一个参数,一般都使用cls来指定,使用装饰器赋值类方法,相当于: foo = classmethod(foo)
    @classmethod
    def foo(cls):
        print('calling class method foo()')
        print('foo() is part of class:',cls.__name__)
>>> tsm  = TestStaticMethod()
# 可以通过类名加方法的方式调用
>>> TestStaticMethod.foo()
calling static method foo()
# 通过类的实例来调用静态方法
>>> tsm.foo()
calling static method foo()
>>> tcm = TestClassMethod()
# 通过类的实例调用类方法
>>> tcm.foo()
calling class method foo()
foo() is part of class: TestClassMethod
# 通过类调用类方法
>>> TestClassMethod.foo()
calling class method foo()
foo() is part of class: TestClassMethod

 

posted @ 2016-04-05 22:10  疯狂的杰瑞  阅读(865)  评论(0编辑  收藏  举报