使用dataclass读取将属性设置为datetime对象的文本文件

2024-10-02 12:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图强迫自己养成使用数据类的习惯。我正在读取一个包含数据行的文本文件,其中两列包含日期。当我将文件读入类时,为什么日期没有转换为datetime对象

import datetime
from dataclasses import dataclass

@dataclass
class AC07:
    NAME: str
    MADE_FROM_DATE: datetime.datetime
    MADE_UPTO_DATE: datetime.datetime
    
counter = 0
deck = []
with open(filename, encoding="latin-1") as file:
    for line in file:
        args = line.strip().split("|")[1:]  # not interested in first column
        data = AC07(*args)
        deck.append(data)
        counter += 1
        if counter == 10:
            break
        
print (type(deck[0].MADE_FROM_DATE))
<class 'str'>
# Expected behavior <class datetime.datetime> 

Tags: 数据infromimportdatetimedatelinecounter
2条回答

现在我更好地理解了@vasco ludovico发布的答案,为了解决我的问题,我使用了下面的代码:

with open(filename, encoding="latin-1") as file:
    for line in file:
        args = line.strip().split("|")[1:]  # not interested in first column
        data = AC07(*args)
        data.MADE_FROM_DATE = datetime.datetime.strptime(data.MADE_FROM_DATE, "%d/%m/%Y")
        deck.append(data)
        counter += 1
        if counter == 10:
            break

请有人纠正我,如果我错了,但我相信数据类不强制类型。在您的示例中,datetime.datetime(几乎)只是一个注释,除了两个实现细节之外。检查documentation。具体来说,

The dataclass() decorator examines the class to find fields. A field is defined as class variable that has a type annotation. With two exceptions described below, nothing in dataclass() examines the type specified in the variable annotation.

这两个例外与强制数据类型无关:

Class variables One of two places where dataclass() actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar. If a field is a ClassVar, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function.

Init-only variables The other place where dataclass() inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type dataclasses.InitVar. If a field is an InitVar, it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level fields() function. Init-only fields are added as parameters to the generated __init__() method, and are passed to the optional __post_init__() method. They are not otherwise used by dataclasses.

相关问题 更多 >

    热门问题