私はそのようなコードを持っています:
class Base:
def do( self ):
self._member1 = 0
self._member2 = 1
class Derived1(Base):
def do(self):
Base.do(self)
self._member3 = 0
self._member4 = 1
class Derived2(Base):
def do(self):
Base.do(self)
self._member3 = 2
self._member4 = 3
class Derived3(Base):
def do(self):
Base.do(self)
self._member3 = 9
self._member4 = 3
など。これが私がやったことです:
class Base(object):
'''Base class.'''
def do(self):
self._member1 = 0
self._member2 = 1
class Derived1(Base): pass
class Derived2(Base): pass
class Derived3(Base): pass
class Derived4(Base): pass
class DerivedFactory(object):
'''Factory to create derived classes.'''
members = \
{
1: (Derived1, 0, 1),
2: (Derived2, 4, 5),
3: (Derived3, 6, 7),
4: (Derived4, 8, 9),
}
def do(self, key=1):
derived = self.members[key][0]()
derived.do() # Perform method from Base
derived._member3 = self.members[key][1]
derived._member4 = self.members[key][2]
print(derived)
print('\t%s' % derived.__dict__)
if __name__ == '__main__':
factory = DerivedFactory()
for key in range(1, 5):
derived = factory.do(key)
しかし、ご覧のとおり完璧ではありません。Derived1、Derived2などを宣言する必要があります。また、複雑すぎるようです。このコードをどのように改良するかについて何かアイデアはありますか?ありがとう!