Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

Python dataclass AttributeError

I have a dataclass set up like this:

from dataclasses import dataclass, field
from typing import List

@dataclass
class stats:
    target_list: List[None] = field(default_factory=list)

When I try to compare the contents of the list like so:

if stats.target_list == None:
    pass

I get AttributeError: type object 'stats' has no attribute 'target_list'

How can I fix this issue? Thanks

question from:https://stackoverflow.com/questions/65891632/python-dataclass-attributeerror

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're trying to find an attribute named target_list on the class itself. You want to testing an object of that class. For example:

from dataclasses import dataclass, field
from typing import List

@dataclass
class stats:
    target_list: List[None] = field(default_factory=list)


def check_target(s):
    if s.target_list is None:
        print('No target list!')
    else:
        print(f'{len(s.target_list)} targets')


StatsObject1 = stats()
StatsObject2 = stats(target_list=['a', 'b', 'c'])

check_target(StatsObject1)
check_target(StatsObject2)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...