zoukankan      html  css  js  c++  java
  • 类的属性和方法

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

    >>> 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
  • 相关阅读:
    Developers’ Musthave: the new Microsoft AllInOne Code Framework Sample Browser and 3500+ samples
    8774
    DCOM
    9个最棒的代码片段资源网站
    WCF中的几种地址总结
    如何用C#编写DCOM服务器
    C++ DCOM服务器和C#客户端互操作完全解释
    理解Prism中MVVM的Command与CommandParameter
    WCF REST 基础教程
    细说ASP.NET Forms身份认证
  • 原文地址:https://www.cnblogs.com/OnOwnRoad/p/5356989.html
Copyright © 2011-2022 走看看