5

I have 2 very similiar classes: A and B:

import attr
@attr.s
class A(object):
   x = attr.ib()
   y = attr.ib()

@attr.s
class B(object):
   x = attr.ib()
   z = attr.ib()
   y = attr.ib(default=None)

As you can see, they share 2 attributes (x and y), but in class A y attribute is positional while in B it's optional.

I want to group these classes in one super class, but if I try making class B inherit from class A I get the following error:

SyntaxError: duplicate argument 'y' in function definition

Added the code I used for raising the error:

@attr.s
class A(object):
    x = attr.ib()
    y = attr.ib()


@attr.s
class B(A):
    z = attr.ib()
    y = attr.ib(default=None)

So my question is: is it possible group these classes in one super class using attrs module? if no, would you suggest me just grouping them like the 'old fashion' way instead (implementing init methods on my own)?

Many thanks!

NI6
  • 2,477
  • 5
  • 17
  • 28
  • Best thing thought of so far is make both classes inherit from class C that defines property x in it – NI6 Nov 09 '17 at 14:15

1 Answers1

8

It’s not entirely clear to me what behavior you expect? If you want to overwrite A's y, I have good news because that should work in attrs 17.3 that has been released just yesterday:

>>> @attr.s
... class A(object):
...     x = attr.ib()
...     y = attr.ib()
...
...
... @attr.s
... class B(A):
...     z = attr.ib()
...     y = attr.ib(default=None)

>>> B(1, 2)
B(x=1, z=2, y=None)
hynek
  • 3,647
  • 1
  • 18
  • 26