我有这样的代码:
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 等。而且它似乎过于复杂。您对如何改进此代码有任何想法吗?谢谢!