简体   繁体   English

初始化 class 属性而不创建构造函数 python

[英]Initialize class properties without creating a constructor python

I have this code:我有这个代码:

class MyClass:
    a = None
    b = None

now I have this part in my code:现在我的代码中有这一部分:

my_class_instance = MyClass(a=3, b=5)

I am getting this error:我收到此错误:

TypeError: MyClass() takes no arguments

Is there a way to initialize MyClass with values for a and b without creating a constructor?有没有办法在不创建构造函数的情况下用ab的值初始化MyClass

One possibility is a dataclass:一种可能性是数据类:

from dataclasses import dataclass

@dataclass
class MyClass:
    a: int
    b: int

mc = MyClass(a=3, b=5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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