Python内蔵関数(11)-classmethod

1548 ワード

英語ドキュメント:
classmethod(function)
Return a class method for function.
A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C: 
    @classmethod 
    def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.
It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.
説明:
  • classmethodは、クラスメソッド
  • としてメソッドを示す装飾関数である.
  • クラスメソッドの最初のパラメータはクラスオブジェクトパラメータであり、メソッドが呼び出されると自動的にクラスオブジェクトが転送され、パラメータ名はcls
  • と規定する.
  • メソッドがクラスメソッドとして示す場合、そのメソッドはクラスオブジェクト(C.f()など)によって呼び出されてもよいし、クラスのインスタンスオブジェクトによって呼び出されてもよい(C()など).f())
  • >>> class C: 
          @classmethod 
          def f(cls,arg1): 
              print(cls) 
              print(arg1) 
    >>> C.f(' ')
    
     
    >>> c = C()
    >>> c.f(' ')
    
     
    
  • クラスが継承すると、サブクラスは親クラスのクラスメソッドを呼び出すこともできるが、最初のパラメータはサブクラスのクラスオブジェクト
  • に伝達される.
    >>> class D(C): 
           pass
    >>> D.f(" ")