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.
CodePudding user response:
In your example, you will get an error when trying to call the show method on an instance of C because the self parameter is not defined in the method definition.
The self parameter is a convention used in Python to refer to the instance of the object on which a method is being called. It is automatically passed to the method when the method is called on an instance of the object.
To fix this error, you need to add the self parameter to the method definition in the A class like this:
class A:
def show(self):
print(self.number)
class C(A):
number = 5
c = C()
c.show()
With this change, the show method will be able to access the number attribute of the C instance through the self parameter. When you call c.show(), it will print the value of c.number, which is 5.
Keep in mind that if you override the number attribute in an instance of C, the value of the number attribute for that instance will be used instead of the value inherited from the A class. For example:
c = C()
c.number = 10
c.show() # Output: 10
In this case, the value of c.number is 10, which is what will be printed by the show method.
CodePudding user response:
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