数据级参数是否有别名或名称参数?
我有一个接受很多参数的类,在初始化方法中,我将它们加载到不同命名的参数中。我知道这可能是一个糟糕的设计,但我现在无法改变。我尝试了很多东西,但实际上没有做任何事情。是否可以在数据类别中进行?
class MyClass:
def __init__(self, vp):
self.viewport = vp
我知道这不是Dataclass的意图行为,但我想知道是否可以进行一些解决方法。
我想拥有的是Dataclass中的映射:
@dataclass
class MyClass:
viewport:str = "" # this should get the value from vp argument if possible
so when I call:
mc = MyClass(vp="foo")
print(mc) should return (MyClass(viewport="foo"))
I have a class that accepts a lot of params, and in init method I'm loading them in differently named params. I know it might be a bad design or whatever, but I can't change that right now. I've tried a lot of stuff but nothing really did the thing. Is it possible to do it within dataclasses?
class MyClass:
def __init__(self, vp):
self.viewport = vp
I know that this is not intended behaviour of dataclass but I'm wondering if it's possible to make some workaround.
What I'd like to have is this mapping within dataclass:
@dataclass
class MyClass:
viewport:str = "" # this should get the value from vp argument if possible
so when I call:
mc = MyClass(vp="foo")
print(mc) should return (MyClass(viewport="foo"))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 a>对于
vp
别名。如果您需要定义许多别名,也可以编写自己的装饰器,该装饰师使用
field.metadata
喜欢:You could use an
InitVar
for thevp
alias.If you need to define many aliases, you could also write your own decorator that uses
Field.metadata
like so:这可以工作吗?
Would this work?
我看不到这将是一个好主意的任何上下文,但是您可以这样做:
哪个将返回:
I don't see any context where this would be a good idea, but you can do it in this way:
Which will return: