Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
class Multiton( object ):
__instances = {}
def __new__( cls, key ):
if not key in cls.__instances:
cls.__instances[key] = object.__new__(cls, key)
return cls.__instances[key]
def __init__(self, key):
self.key = key
@classmethod
def debug_instances(cls):
for k, v in cls.__instances.items():
print v
class MultitonErbe( Multiton ):
#(...)
@classmethod
def sth_useful(cls):
for k, v in cls.__instances.items():
print v
>>> Multiton.debug_instances()
funktioniert!
>>> MultitonErbe.debug_instances()
funktioniert!
>>> MultitonErbe.sth_useful()
(...)
AttributeError: type object 'MultitonErbe' has no attribute '_MultitonErbe__instances'
Der Sinn des name mangling bei klassenvariablen ist der schutz der variable.
Und das möchte ich tun.
Wenn du es so genau nimmst, gibt es in Java auch keine privaten variablen (afaik kann man über reflection an die privaten variablen kommen) und in C++ geht das mit sicherheit auch ... wie auch immer ...
Der Sinn des "name mangeling" ist *nicht* Zugriffsschutz, sondern dass der Name in Subklassen wiederverwendet werden kann, ohne das Kollisionen entstehen. Genau das willst Du ja offensichtlich nicht, also nimm keine zwei Unterstriche.
habe jetzt also den doppelten underscore in einen einfachen geändert.
Jetzt gibt aber MultitonErbe.sth_useful() auch die instanzen von
Dummy(Multiton) aus.
Was mache ich falsch?
(ich möchte nicht explizit in sth_useful() testen ob _instances.item() instanz von MutlitonErbe ist.)
class Multiton( object ):
_instances = {}
def __new__( cls, key ):
if not key in cls._instances:
cls.__instances[key] = object.__new__(cls, key)
return cls._instances[key]
def __init__(self, key):
self.key = key
@classmethod
def debug_instances(cls):
for k, v in cls._instances.items():
print v
class Dummy( Multiton ):
pass
class MultitonErbe( Multiton ):
#(...)
@classmethod
def sth_useful(cls):
for k, v in cls._instances.items():
print v
class Multiton( object ):
# _instances = {}
def __new__(cls, key):
if not hasattr(cls, '_instances'):
cls._instances = dict()
if key not in cls._instances:
cls._instances[key] = object.__new__(cls, key)
return cls._instances[key]