如果你想使用继承来解决你的问题,你需要从编写一个合适的AngryDog 子类开始,你可以使用它来构建健全的实例。
下一步是添加一个from_dogclassmethod,可能是这样的:
from dataclasses import dataclass, asdict
@dataclass(frozen=True)
class AngryDog(Dog):
bite: bool = True
@classmethod
def from_dog(cls, dog: Dog, **kwargs):
return cls(**asdict(dog), **kwargs)
但是按照这种模式,您将面临一个特定的极端情况,您自己已经通过whatever 参数指出了这种情况。当重新调用Dog 构造函数时,任何InitVar 都将在asdict 调用中丢失,因为它们不是该类的正确成员。事实上,任何发生在数据类的__post_init__(InitVars 所在的位置)中的任何事情都可能导致错误或意外行为。
如果只是像过滤或删除 cls 调用中的已知参数这样的小事情,并且预计父类不会更改,您可以尝试在 from_dog 中处理它。但从概念上讲,没有办法为这种from_instance 问题提供通用解决方案。
Composition 从数据完整性的角度来看是没有错误的,但考虑到手头的确切问题,它可能是单一的或笨拙的。这样的 dog-extension 不能代替适当的 dog-instance 使用,但我们可以将其鸭型化成正确的形状以备不时之需:
class AngryDogExtension:
def __init__(self, dog, bite=True):
self.dog = dog
self.bite = bite
def __getattr__(self, item):
"""Will make instances of this class bark like a dog."""
return getattr(self.dog, item)
用法:
# starting with a basic dog instance
>>> dog = Dog(name='pluto', blabla=1, whatever=['a', 'b'])
>>> dog_e = AngryDogExtension(d)
>>> dog_e.bite # no surprise here, just a regular member
True
>>> dog_e.name # this class proxies its dog member, so no need to run `dog_e.dog.name`
pluto
但归根结底,isinstance(dog_e, Dog) 将返回 False。如果您承诺让该调用返回True,那么有一些高级技巧可以帮助您,并使任何继承您代码的人讨厌您:
class AngryDogDoppelganger(Dog):
def __init__(self, bite, **kwargs):
if "__dog" in kwargs:
object.__setattr__(self, "__dog", kwargs["__dog"])
else:
object.__setattr__(self, "__dog", Dog(**kwargs))
object.__setattr__(self, "bite", bite)
@classmethod
def from_dog(cls, dog, bite=True):
return cls(bite, __dog=dog)
def __getattribute__(self, name):
"""Will make instances of this class bark like a dog.
Can't use __getattr__, since it will see its own instance
attributes. To have __dog work as a proxy, it needs to be
checked before basic attribute lookup.
"""
try:
return getattr(object.__getattribute__(self, "__dog"), name)
except AttributeError:
pass
return object.__getattribute__(self, name)
用法:
# starting with a basic dog instance
>>> dog = Dog(name='pluto', blabla=1, whatever=['a', 'b'])
# the doppelganger offers a from_instance method, as well as
# a constructor that works as expected of a subclass
>>> angry_1 = AngryDogDoppelganger.from_dog(dog)
>>> angry_2 = AngryDogDoppelganger(name='pluto', blabla=1, whatever=['a', 'b'], bite=True)
# instances also bark like at dog, and now even think they're a dog
>>> angry_1.bite # from subclass
True
>>> angry_1.name # looks like inherited from parent class, is actually proxied from __dog
pluto
>>> isinstance(angry_1, Dog) # ?
True
大多数添加数据类的方法,例如 __repr__,将被破坏,包括在 dataclass.asdict 甚至只是 vars 之类的东西中插入分身实例 - 所以使用风险自负。