-2

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?

Kenny Smith
  • 729
  • 3
  • 9
  • 23
  • 3
    https://docs.python.org/3/library/dataclasses.html? Maybe a https://docs.python.org/3/library/collections.html#collections.namedtuple? – jonrsharpe Dec 07 '21 at 11:35

1 Answers1

6

One possibility is a dataclass:

from dataclasses import dataclass

@dataclass
class MyClass:
    a: int
    b: int

mc = MyClass(a=3, b=5)
Passerby
  • 808
  • 1
  • 5
  • 9
  • Thanks. Do I have to declare the properties type? what if I want it to be generic? – Kenny Smith Dec 07 '21 at 12:04
  • 1
    https://stackoverflow.com/questions/49931096/how-to-add-a-dataclass-field-without-annotating-the-type answers that question. – Passerby Dec 07 '21 at 12:12
  • 1
    @Kenny in theory, you can wrap The annotation in the string in order to forward declare it, so for example `a : ‘I really have no idea what I’m doing!’` and Python will like that just fine. – rv.kvetch Dec 07 '21 at 16:50
  • note that replacing angular quotes with normal quotes `'` is necessary, because I was typing on my phone. – rv.kvetch Dec 07 '21 at 19:12
  • Though in all fairness, you can also annotate a field as `typing.Any` if you don't know beforehand what type the variable is going to have. In practice however, generally you can narrow down it down to a few possible types, so in that case you can use `typing.Union` instead. For example, `a: 'int | str | bool'` if you know that field `a` can be any of those types, and so an IDE can also offer you type hints accordingly. In Python 3.10, you can unwrap it from a string and just declare it explicitly, as the pipe `|` operator is supported for builtin types. – rv.kvetch Dec 07 '21 at 19:14