2012-04-14 2 views
1

나는 생성자 앞에서 클래스의 정적 필드/변수를 선언하는 데 사용됩니다. 파이썬에서 그렇게하면 오류가 발생합니다.생성자 전에 정적 변수를 선언하려면 어떻게해야하며 클래스의 본문을 참조하려면 어떻게해야합니까?

여기에 예제 클래스는 다음과 같습니다

class StringCompare: 

    methods = OrderedDict() 
    # ERROR!: 
    #methods['equals'] = equals 
    #methods['ends with'] = endswith 
    #methods['starts with'] = startswith 
    #methods['contains'] = contains 

    @staticmethod 
    def equals(a, b): 
     return a == b 

    @staticmethod 
    def contains(a, b): 
     return a.find(b) != -1 

    @staticmethod 
    def startswith(a, b): 
     return a.startswith(b) 

    @staticmethod 
    def endswith(a, b): 
     return a.endswith(b) 

    methods['equals'] = equals 
    methods['ends with'] = endswith 
    methods['starts with'] = startswith 
    methods['contains'] = contains 

는 더 우아한 방법 ( StringCompare. 각 액세스 VAR 접두어 전체 클래스 직후 모든 문을 배치 제외)이 있습니까?

여기에서 가장 좋은 방법은 무엇입니까? 이 오류가 발생

class Type(InlineFragment): 

    # primitive types get None as package name 
    def __init__(self, packageName, name, genericType=None): 

     ... 

    def ... 

    primitive = { 
     'Character': Type(None, 'char'), 
     'Byte'  : Type(None, 'byte'), 
     'Short' : Type(None, 'short'), 
     'Integer' : Type(None, 'int'), 
     'Long'  : Type(None, 'long'), 
     'Boolean' : Type(None, 'boolean'), 
     'Float' : Type(None, 'float'), 
     'Double' : Type(None, 'double'), 
    } 

:


더 복잡한 경우는 같은 클래스 내에서 생성자를 호출 할 때이 될 것

\jpa_export_fragments.py", line 361, in Type 
    'Character' : Type(None, 'char'), 
NameError: name 'Type' is not defined 

이 작동해야하지만, 클래스 외부에이 코드를 넣어서 만 해결할 수 있습니다.

+2

유용한 예제를 제공하려고했지만 실제로는 "파이썬은 다릅니다. 독특한 스타일을 배우십시오." 파이썬에서는 모든 것이 클래스에 있어야하는 것은 아닙니다. 'primatives'는 아마도'Type'의 정의에 따라 모듈 수준의 변수 여야합니다. – agf

답변

3

일반적으로 해결책은 class decorators을 사용하는 것입니다. 귀하의 예를 들어, 당신은 아마 클래스 메소드와 조합 할 :

def apply_method(attr): 
    def apply_to(cls): 
     setattr(cls, attr, getattr(cls, '_' + attr)()) 
     return cls 
    return apply_to 

@apply_method('primative') 
class Type(object): 

    def __init__(self, *args): 
     pass 

    @classmethod 
    def _primative(cls): 
     return { 
    'Character': cls(None, 'char'), 
    'Byte'  : cls(None, 'byte'), 
    'Short' : cls(None, 'short'), 
    'Integer' : cls(None, 'int'), 
    'Long'  : cls(None, 'long'), 
    'Boolean' : cls(None, 'boolean'), 
    'Float' : cls(None, 'float'), 
    'Double' : cls(None, 'double'), 
     } 

첫 번째 예는 매우-않은 파이썬 보이는, 그래서 나는 그의 장식을 제안 주저. 대신 서브 클래스가 str이 필요합니까?

class StringCompare(str): 
    # none of these are any different from the normal string operations 
    # you would really only override ones that are different. 

    def __eq__(self, other): 
     return super(StringCompare, self).__eq__(other) 

    def __contains__(self, other): 
     return self.find(other) != -1 

    def startswith(self, other): 
     return super(StringCompare, self).startswith(other) 

    def endswith(self, other): 
     return super(StringCompare, self).endswith(other) 


print StringCompare('boogaloo').startswith('boo') # True 
관련 문제