I've got a class that stores some Qt controls, so:
class Controls:
def __init__(self):
self.label = QLabel()
Then I can do:
x = Controls()
x.label.setText("Hello")
This works. The class actually has dozens of controls, not just the one I've used for illustration, so I wanted to use the more succinct dataclass notation:
@dataclass(frozen=True, init=False)
class Controls:
label: QLabel
but having done this, I get an error:
AttributeError: 'Controls' object has no attribute 'label'
I've tried initialising the field ( = QLabel()
), I've also tried using field
with default
or default_factory
, with no joy.
I wondered if anyone knew what the problem was?
You have to let the constructor be implemented(remove init=False
):
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Controls:
label: QLabel = field(default_factory=QLabel)
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.