__init__() takes from 1 to 2 positional arguments but 4 were given after refactorizing class to be under base class

87 Views Asked by At

I have a class that currently looks something like this:

import attr

@attr.s
class my_class(object):
  var1 = attr.ib(default=5)
  var2 = attr.ib(default=5)
  var3 = attr.ib(default=5)
  @classmethod
  def func(cls):
    cls(1, 2, 3)

my_class.func()

I need to create an abstract base class and refactor var1, var2 to be under base class. var3 will stay as is.

So I tried to do this:

import attr
from abc import ABC, abstractmethod

@attr.s
class base(ABC, object):
  var1 = attr.ib(default=5)
  var2 = attr.ib(default=5)

@attr.s
class my_class(base):
  var3 = attr.ib(default=5)
  @classmethod
  def func(cls):
    cls(1, 2, 3)

my_class.func()

but it gives the error

TypeError: __init__() takes from 1 to 2 positional arguments but 4 were given

It seems I'm not calling cls properly here since now there's only var3 associated with my_class. If I want to initialize var1 and var2, how I do it in an analogous way?

1

There are 1 best solutions below

3
Tom McLean On

Use attr.define

import attr
from abc import ABC, abstractmethod

@attr.define
class base(ABC, object):
  var1 : int
  var2 : int

@attr.define
class my_class(base):
  var3 = attr.ib(default=5)
  @classmethod
  def func(cls):
    return cls(1, 2, 3)

res = my_class.func()

print(res)