Copying values from the object of base class in Python
本问题已经有最佳答案,请猛点这里访问。
是否有方法将属性值从基类对象复制到派生类对象?
1 2 3 4 5 6 7 8 9 10 11 12 | class Base(): def __init__(self): self.a = 10 self.b = None class Derived(Base): self.c = 30 def main(): base = Base() base.b = 20 derived = Derived(base) |
我试图找到一种更像Python般的方法来复制基类对象的值,因为基类有许多变量,但我找不到一种简洁的方法。
我希望变量"derived"的值为"a=10b=20c=30"。
这不是继承的方法。您正在将基类的实例传递给派生类的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Base(): def __init__(self): self.a = 10 class Derived(Base): def __init__(self): super(Derived, self).__init__() # calls Base.__init__ self.b = 'abc' def main(): base = Base() derived = Derived() |
使用默认参数怎么样?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Base(): def __init__(self, a=10): self.a = a class Derived(Base): def __init__(self, a=10, b=None): super().__init__(a) # python 3 # Base.__init__(self, a) # python 2 self.b = b or 'abc' def main(): base = Base() derived = Derived() print(base.a) print(derived.a, derived.b) main() # output: # 10 # 10 abc |
还要注意如何调用负责设置