Python:从基类数据类继承的数据类,如何将值从基类升级到新类? [英] Python: Dataclass that inherits from base Dataclass, how do I upgrade a value from base to the new class?

查看:71
本文介绍了Python:从基类数据类继承的数据类,如何将值从基类升级到新类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将值从基础数据类升级到继承自它的数据类?

How can I upgrade values from a base dataclass to one that inherits from it?

示例(Python 3.7.2)

Example (Python 3.7.2)

from dataclasses import dataclass

@dataclass
class Person:
    name: str 
    smell: str = "good"    

@dataclass
class Friend(Person):

    # ... more fields

    def say_hi(self):        
        print(f'Hi {self.name}')

friend = Friend(name='Alex')
f1.say_hi()

打印嗨亚历克斯"

random_stranger = Person(name = 'Bob', smell='OK')

返回 random_stranger "Person(name='Bob',slot='OK')"

return for random_stranger "Person(name='Bob', smell='OK')"

如何将 random_stranger 变成朋友?

How do I turn the random_stranger into a friend?

Friend(random_stranger)

返回Friend(name=Person(name='Bob',sole='OK'),sleem='good')"

returns "Friend(name=Person(name='Bob', smell='OK'), smell='good')"

我想得到Friend(name='Bob',small='OK')"作为结果.

I'd like to get "Friend(name='Bob', smell='OK')" as a result.

Friend(random_stranger.name, random_stranger.smell)

有效,但如何避免必须复制所有字段?

works, but how do I avoid having to copy all fields?

或者我是否可能无法在从数据类继承的类上使用 @dataclass 装饰器?

Or is it possible that I can't use the @dataclass decorator on classes that inherit from dataclasses?

推荐答案

工厂方法模式,并且可以使用@classmethod关键字直接在python类中实现.

What you are asking for is realized by the factory method pattern, and can be implemented in python classes straight forwardly using the @classmethod keyword.

只需在您的基类定义中包含一个数据类工厂方法,如下所示:

Just include a dataclass factory method in your base class definition, like this:

import dataclasses

@dataclasses.dataclass
class Person:
    name: str
    smell: str = "good"

    @classmethod
    def from_instance(cls, instance):
        return cls(**dataclasses.asdict(instance))

从这个基类继承的任何新数据类现在都可以创建彼此的实例[1]像这样:

Any new dataclass that inherit from this baseclass can now create instances of each other[1] like this:

@dataclasses.dataclass
class Friend(Person):
    def say_hi(self):        
        print(f'Hi {self.name}')

random_stranger = Person(name = 'Bob', smell='OK')
friend = Friend.from_instance(random_stranger)
print(friend.say_hi())
# "Hi Bob"


[1] 如果您的子类引入了没有默认值的新字段,您尝试从子类实例创建父类实例,或者您的父类具有 init-only 参数,则它将不起作用.

这篇关于Python:从基类数据类继承的数据类,如何将值从基类升级到新类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆