0

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')

2
  • You want to update default value or the value in the instance? Commented Mar 13, 2023 at 7:45
  • i want to update the value in the instance Commented Mar 13, 2023 at 8:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Niyas I want to create empty list first and then update the list with the values passed from user side. looking for a solution how to create empty list & update the list at later point of time using dataclasses
got the solution. Updated in description

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.