[英]How do I create an instance of a subclass from an instance of a superclass?
我上了兩節課,父母和孩子。 我想知道的是,是否有可能使用父類初始化子類。 這是我的代碼:
class Pc:
def __init__(self, brand, processor, price):
self.brand = brand
self.processor = processor
self.price = price
class Laptop(Pc):
def __init__(self,brand,processor,price, battery):
Pc.__init__(self,brand,processor,price)
self.battery = battery
現在,我可以使用以下方法初始化Laptop類:
b = Laptop('brand','processor','price')
但這對我似乎沒有多大用處,我的老師也沒有很好地解釋它。 我很想知道是否可以做這樣的事情:
a = Pc("brand","processor","price")
b = Laptop(a, "battery")
當我用我的代碼嘗試此操作時,出現錯誤。 甚至有可能這樣做嗎?
你可以做:
class Laptop(Pc):
def __init__(self, pc, battery):
Pc.__init__(self, pc.brand, pc.processor, pc.price)
self.battery = battery
這將從您提供給構造函數的pc
參數初始化繼承的屬性。
如果希望使用short或long方法,則應定義構造方法以采用關鍵字參數,然后根據所使用的形式使用if
語句適當地調用Pc.__init__()
。
python中沒有內置的機制來實現您想要的功能,因此您必須自己完成操作或找到第三方解決方案。
一個好的方法是,我可能會在超類上添加一個可以克隆對象的類方法:
class Pc:
@classmethod
def clone(cls, target, *extra_args, **extra_kwargs):
return cls(
target.brand, target.processor, target.price, *extra_args,
**extra_kwargs)
def __init__(self, brand, processor, price):
self.brand = brand
self.processor = processor
self.price = price
class Laptop(Pc):
def __init__(self, brand, processor, price, battery):
super(Laptop, self).__init__(brand, processor, price)
self.battery = battery
a = Pc("brand","processor","price")
b = Laptop.clone(a, 'battery')
print(b.battery)
但是您可能會發現您開始遇到初始化參數的麻煩。 我建議將__init__()
必需參數減至最少,然后再配置必要的屬性:
a = Pc()
a.brand = 'brand'
# etc.
有幾種選擇
如果要保留當前行為,則在添加新行為時可以使用* arg,例如
class Laptop(Pc): def __init__(self, *argv ): if len(argv) == 4: #the current one brand, processor, price, battery = argv elif len(argv) == 2: #the new one pc, battery = argv brand, processor, price = pc.brand, pc.processor, pc.price else: raise TypeError Pc.__init__(self,brand,processor,price) self.battery = battery
和使用一樣簡單
a = Pc("brand","processor","price") b = Laptop(a, "battery")
制作一個類方法來處理這種情況
class Laptop(Pc): def __init__(self,brand,processor,price, battery): Pc.__init__(self,brand,processor,price) self.battery = battery @classmethod def from_pc_and_battery(cls, pc, battery): return cls( pc.brand, pc.processor, pc.price, battery)
用這個,就像這樣
a = Pc("brand","processor","price") b = Laptop.from_pc_and_battery(a, "battery")
您以某種駭人聽聞的方式進行操作:
import copy
a = Pc("brand","processor","price")
b = copy.deepcopy(a)
b.__class__ = Laptop()
b.battery = battery
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.