我目前正在尝试使用Python 3.7中引入的新数据类结构.我目前坚持尝试做一些父类的继承.看起来参数的顺序是由我当前的方法拙劣的,这样子类中的bool参数在其他参数之前传递.这导致类型错误.
from dataclasses import dataclass
@dataclass
class Parent:
name: str
age: int
ugly: bool = False
def print_name(self):
print(self.name)
def print_age(self):
print(self.age)
def print_id(self):
print(f'The Name is {self.name} and {self.name} is {self.age} year old')
@dataclass
class Child(Parent):
school: str
ugly: bool = True
jack = Parent('jack snr', 32, ugly=True)
jack_son = Child('jack jnr', 12, school = 'havard', ugly=True)
jack.print_id()
jack_son.print_id()
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我得到了这个TypeError:
TypeError: non-default argument 'school' follows default argument
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
from typing import Optional
@dataclass
class Event:
id: str
created_at: datetime
updated_at: Optional[datetime]
#updated_at: datetime = field(default_factory=datetime.now) CASE 1
#updated_at: Optional[datetime] = None CASE 2
@dataclass
class NamedEvent(Event):
name: str
Run Code Online (Sandbox Code Playgroud)
创建事件实例时,我通常不会有updated_at字段。current time在数据库中进行插入时,我可以传递作为默认值或添加一个值,并在对象的后续使用中获取它。哪种方法更好?根据我的理解,我无法在不通过case1 和 case2 中的 updated_at字段的NamedEvent情况下创建实例,因为我在 name 字段中没有默认值。
我在处理 ETL 管道时偶然发现了一个问题。我正在使用数据类dataclass来解析 JSON 对象。JSON 对象的关键字之一是保留关键字。有没有解决的办法:
from dataclasses import dataclass
import jsons
out = {"yield": 0.21}
@dataclass
class PriceObj:
asOfDate: str
price: float
yield: float
jsons.load(out, PriceObj)
Run Code Online (Sandbox Code Playgroud)
这显然会失败,因为yield是保留的。查看数据类field定义,似乎没有任何可以提供帮助的内容。
Go,允许定义JSON字段的名称,不知道里面有没有这样的功能dataclass?