Fernando César
Fernando César

Reputation: 861

Best practices for defining fields only relevant in subclasses in Python

If I have a variable that is only used in a subclass, should I assign None to it in the superclass?

This is minimum example, there other subclasses where ‘number’ is different but the ‘show’ method is still relevant.

class A:
    def show(self):
        print(self.number)

class C(A):
    number = 5

c = C()
c.show()

Should I define number=None in A?

I’m asking because PyCharm keeps showing warnings about this, but I’m not sure filling the superclass with None’s is a good idea.

Upvotes: 2

Views: 325

Answers (1)

chepner
chepner

Reputation: 531848

If A defines a method that requires a particular attribute, A should also be responsible for ensuring that attribute exists. (The value of the attribute does not matter, but don't use None as an arbitrary placeholder; if A doesn't have a good default value, require one be provided to A.__init__.)

class A:
    def __init__(self, n):
        self.number = n

    def show(self):
        print(self.number)


class C(A):
    pass


c = C(5)
c.show()

If number really must be a class attribute, consider using __init_subclass__ to set its value. (While A.number is not defined, this at least forces any subclass to define it.)

class A:
    def __init_subclass__(cls, *, number):
        cls.number = number

    def show(self):
        print(self.number)


class B(A, number=5):
    pass

Upvotes: 1

Related Questions