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
이 작동해야하지만, 클래스 외부에이 코드를 넣어서 만 해결할 수 있습니다.
유용한 예제를 제공하려고했지만 실제로는 "파이썬은 다릅니다. 독특한 스타일을 배우십시오." 파이썬에서는 모든 것이 클래스에 있어야하는 것은 아닙니다. 'primatives'는 아마도'Type'의 정의에 따라 모듈 수준의 변수 여야합니다. – agf