Python では、クラス属性を 2 つの異なる方法で初期化していることに気付きました。
最初の方法は次のようになります:
class MyClass:
__element1 = 123
__element2 = "this is Africa"
def __init__(self):
#pass or something else
他のスタイルは次のようになります。
class MyClass:
def __init__(self):
self.__element1 = 123
self.__element2 = "this is Africa"
クラス属性を初期化する正しい方法はどれですか?
ベストアンサー1
どちらの方法も必ずしも正しいか間違っているわけではなく、単に 2 種類の異なるクラス要素であるだけです。
- メソッド外の要素は
__init__
静的要素であり、クラスに属します。 - メソッド内の要素は
__init__
オブジェクト (self
) の要素であり、クラスには属しません。
いくつかのコードでより明確に確認できます:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
ご覧のとおり、クラス要素を変更すると、両方のオブジェクトが変更されました。ただし、オブジェクト要素を変更しても、もう一方のオブジェクトは変更されませんでした。