简体   繁体   中英

Python instance attribute assignment in class created using @dataclass

I have just started using @dataclass decorator. This is my without dataclass implementation

class Myclass:

    def __init__(self, path: str = None, company_name: List = None):

        self.path = path
        self.company_name = company_name

        if path is not None:
            with open(self.path, 'r') as f:
                self.data = yaml.load(f, Loader=yaml.FullLoader)
        else:
            self.data = {'company': self.company_name}

So here, I am making an instance attribute assignment.

c = Myclass(path = '/home/akash/project/stock-analysis/data/sample_company.yaml')
c.data
>>>{'company': ['ADANIGREEN', 'HDFCAMC', 'WHIRLPOOL', 'APLAPOLLO', 'LALPATHLAB']}

The @dataclass equivalent which I manage is

@dataclass
class Myclass:
    path: str=None
    company_name: List=None
        
    def __post_init__(self):
        if self.path is not None:
            with open(self.path, 'r') as f:
                self.data = yaml.load(f, Loader=yaml.FullLoader)
        else:
            self.data = {'company': self.company_name}

It gives exactly the same output (which is expected)

c = Myclass(path = '/home/akash/project/stock-analysis/data/sample_company.yaml')
c.data
>>>{'company': ['ADANIGREEN', 'HDFCAMC', 'WHIRLPOOL', 'APLAPOLLO', 'LALPATHLAB']}

So, am I doing it in the right way?

If you want to include data as a field, you can initialize it with field(init=False) to indicate that it's value is not an argument to __init__ :

from dataclasses import dataclass, field
from typing import List, Dict
import yaml

@dataclass
class Myclass:
    path: str = None
    company_name: List[str] = None
    data: Dict[str, List[str]] = field(init=False)
        
    def __post_init__(self):
        if self.path is not None:
            with open(self.path, 'r') as f:
                self.data = yaml.load(f, Loader=yaml.FullLoader)
        else:
            self.data = {'company': self.company_name}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM