Home > Blockchain >  Initialize class properties without creating a constructor python
Initialize class properties without creating a constructor python

Time:12-08

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?

CodePudding user response:

One possibility is a dataclass:

from dataclasses import dataclass

@dataclass
class MyClass:
    a: int
    b: int

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