Python:如何将所有属性从基类复制到派生类 [英] Python: How to copy all attibutes from base class to derived one
问题描述
我想实现以下:
#!/usr/bin/python
class SuperHero(object):
def setName(self, name):
self.name = name
def getName(self):
return self.name
class SuperMan(SuperHero):
pass
if __name__ == "__main__":
sh = SuperHero()
sh.setName("Clark Kent")
sm = SuperMan(sh) # This does *not* work in real python
print sm.getName() # prints "Clark Kent"
我必须逐一复制属性,还是有更好的方法?
Do I have to copy the attributes one by one or is there a better way to do it?
推荐答案
我更喜欢显式的解决方案 - 复制一个。 Martijn Pieters
的解决方案很不错,但随着时间的推移,你的 __ dict __
可能会增长,你可能不想复制它的所有内容(或更糟 - 忘记这个事实,并体验一些讨厌的副作用)。除了Python的Zen说: Explicit比隐式更好。
。
I'd prefer explicit solution - copying one by one. Martijn Pieters
's solution is nice, but with time your __dict__
may grow and you may not want to copy all it's content (or worse - forget about this fact and experience some nasty side effects). Besides the Zen of Python says: Explicit is better than implicit.
.
, 对?所以你的代码可能更pythonic如果你使用他们:
Side note - you are aware of properties, right? So your code could be more pythonic if you used them:
class SuperHero(object):
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
sh = SuperHero()
sh.name = "Clark Kent"
这篇关于Python:如何将所有属性从基类复制到派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!