-1

getting attribute error while accessing the class member my_list which is initialized using default_factory method

I want to create a Empty list and update the list with values passed from the user using dataclass

from dataclasses import dataclass, field

@dataclass
class MyClass:
    my_list: list[int] = field(default_factory=list)
    my_string: str = ""

    @classmethod
    def update_my_list(cls, new_list: list[int]):
        for index, _ in enumerate(new_list):
            cls.my_list[index] = new_list[index]
        return cls(new_list, "NO")


my_object = MyClass()
print(my_object.my_list)     # Output: []
print(my_object.my_string)   # Output: ""

my_object = MyClass.update_my_list([4, 5, 6]) -> **AttributeError: type object 'MyClass' has no attribute 'my_list'**
print(my_object) 

How to resolve this issue?

Found working solution:

from dataclasses import dataclass, field

@dataclass
class MyClass:
    my_list: list = field(default_factory=list)
    my_string: str =''

    @classmethod
    def update_my_list(cls, new_list: list):
        cls.my_list = new_list
        return cls(new_list, "NO")


my_object = MyClass()
print(my_object.my_list)     # Output: []
print(my_object.my_string)   # Output: ""

my_object = MyClass.update_my_list([4, 5, 6])
print(my_object)

output : MyClass(my_list=[4, 5, 6], my_string='NO')

1 Answers1

1

I think you misunderstood how dataclass works in python.

When you write a class with dataclass as decorator, it convert your class from

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

to

# dataclass with also add other methods like __repr__ but that's skipped for brevity
class InventoryItem:
    def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
        self.name = name
        self.unit_price = unit_price
        self.quantity_on_hand = quantity_on_hand

So the members name, unit_price etc are exist only on InventoryItem class instance(ie, self).

See also

Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46