2017-04-02 3 views
0
class A(object): 
    def __init__(self, val): 
     self.val = A.plus_one(val) 

    @staticmethod 
    def plus_one(val): 
     return val + 1 

クラス内に静的メソッドを定義し、任意の場所で使用できます。私の質問は、なぜこのクラス内でこの静的メソッドを使用しても、つまりメソッド名の前にA.を追加しても、静的メソッドの名前空間を確保する必要があるということです。なぜPythonで静的メソッドの名前空間を使用しますか?

私の考えは、クラス内の静的メソッド名は、のように名前空間である必要はありませんように、我々は単にメカニズムを変更することができ、次のとおりです(Pythonは今それをサポートしていませんが):

class A(object): 
    def __init__(self, val): 
     self.val = plus_one(val) 

    @staticmethod 
    def plus_one(val): 
     return val + 1 

マイ直感は、クラス内から呼び出すので、クラスメンバーの優先順位はグローバル関数よりも高くなければならず、したがってあいまいさはありません。なぜPythonが名前空間を強制するのですか?

+0

Pythonでは強制しません。 「裸の」機能を定義することもできます。しかし、静的メソッドを使用すると、コードを整理する追加のレイヤーが可能になります。 – Keith

+0

@キース私はあなたがその質問を誤解していると思う。それは静的メソッドを呼び出すことに関するものです。 (私も混乱していました) –

+2

3つの考え:1)別の方法で、同じ名前のトップレベルメソッドを呼び出すことができますか? 2) 'member()'を呼び出す代わりに 'self.member()'を使う必要があります。 3)静的メソッドでさえ過負荷になる可能性があるので、 'self.plus_one'と' A.plus_one'の間には潜在的な違いがあります。どちらを呼びますか? –

答えて

1

クラス内で定義されたメソッドは、クラスネームスペースで直接実行されるコード(別のメソッド内ではない)以外は、裸の名前でアクセスできません。メソッドを呼び出す場合は、通常、ある種のオブジェクト(インスタンスまたはクラス自体)でメソッドをルックアップする必要があります。異なる種類のメソッドは、異なる種類のルックアップのときの振る舞いが異なります。

class Test(object): 
    def normal_method(self, foo): 
     print("normal_method", self, foo) 
     # none of the method names are valid here as bare names, only via self or Test 
     try: 
      class_method(type(self), foo) # raises NameError 
     except NameError: 
      pass 

     self.class_method(foo) # this works 
     Test.class_method(foo) # so does this 

    @classmethod 
    def class_method(cls, foo): 
     print("class_method", cls, foo) 
     # from a class method, you can call a method via the automatically provided cls 
     cls.static_method(foo) 

    @staticmethod 
    def static_method(foo): 
     print("static_method", foo) 
     # a static method can only use the global class name to call other methods 
     if isinstance(foo, int) and foo > 0: 
      Test.static_method(foo - 1) 

    # Class level code is perilous. 
    #normal_method('x', 2) # could work in Python 3 (Python 2 checks the type of self) 
          # but it probably won't be useful (since self is not an instance) 
    #class_method('x', 2) # Won't work. A classmethod descriptor isn't directly callable 
    #staticmethod(2)  # Nor is a staticmethod 

# Top level code (these are all valid) 
Test().normal_method(2) # also could be Test.normal_method(Test(), 2) 
Test.class_method(2) # could also be Test().class_method(2) (type of the instance is used) 
Test.static_method(2) # could also be Test().static_method(2) (instance is ignored) 
関連する問題