私はコンストラクターの前にクラスで静的フィールド/変数を宣言するために使用されます。Pythonでこれを行うと、エラーが発生します。
クラスの例を次に示します。
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.
)を付けますか?
ここでのベストプラクティスは何ですか?
より複雑なケースは、同じクラス内からコンストラクターを呼び出そうとする場合です。
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
これは機能するはずですが、このコードをクラスの外に置くことによってのみこれを解決できます。