作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我们有一个来自图书馆的类,
@dataclass(frozen=True)
class Dog:
name: str
blabla : int
# lot of parameters
# ...
whatever: InitVar[Sequence[str]]
pluto = dog_factory() # returns a Dog object
bite
'。
pluto['bite'] = True
将失败,因为数据类被卡住。
class AngryDog(Dog):
# what will come here ?
class AngryDog(Dog):
def __init__(self, dog, bite = True):
copy_construct(dog)
最佳答案
如果你想使用继承来解决你的问题,你需要从写一个正确的 AngryDog
开始。可用于从中构建健全实例的子类。
下一步是添加 from_dog
classmethod ,可能是这样的:
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
提供通用解决方案。问题。
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
.如果您 promise 调用电话返回
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
- 所以使用风险自负。
关于python - 扩展卡住数据类并从基类实例中获取所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62322620/
我是一名优秀的程序员,十分优秀!