I can't seem to find a set of search keywords that provide an answer to this question. I'd like to create a parent class in which a method that uses a class attribute is defined. The child classes will define the values of the class attribute for that child class, using it when calling the method defined in the parent class. How can I do this?
[EDIT: Why do I want to do this? Note that yes, I could create an instance attribute that accomplishes the behavioral goal as shown below. But I want to do this with a class attribute because the code below is just toy example. In my production code I will be creating many thousands of instances of the child classes, and the attribute itself is a large array of data. To my understanding, if I use an instance class it would be a huge waste of memory.]
For example, I want something like this:
class Parent:
multiplier = None
def use_it(self, x):
return Parent.multiplier * x
class Boy(Parent):
multiplier = 2
class Girl(Parent):
multiplier = 3
boy = Boy()
print(boy.use_it(10))
girl = Girl()
print(girl.use_it(10))
That would produce this output:
20
30
The traceback:
TypeError Traceback (most recent call last)
~/scratch/test.py in <module>
13
14 boy = Boy()
---> 15 print(boy.use_it(10))
16
17 girl = Girl()
~/scratch/test.py in use_it(self, x)
2 multiplier = None
3 def use_it(self, x):
----> 4 return Parent.multiplier * x
5
6 class Boy(Parent):
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
Futhermore, if I try to redefine the class attribute when definining the child attribute, it redefines it for all classes that inherit from that parent, not just that specific child class. See this example:
class Parent:
multiplier = None
def use_it(self, x):
return Parent.multiplier * x
class Boy(Parent):
Parent.multiplier = 2
class Girl(Parent):
Parent.multiplier = 3
boy = Boy()
print(boy.use_it(10))
girl = Girl()
print(girl.use_it(10))
Output:
30
30
selfparameter touse_itand accessmultiplierasself.multiplier. Did you try your code before asking?selfargument in theuse_it()toy example (and corrected that in the original post). But changingmultipliertoself.multiplieris not the solution, as that creates an instance attribute, not a class attribute (actually, it creates an error, since it isn't contained in a__init__()method).self.multiplieris the way to go (see my answer). It does not create an instance attribute unless you write to it.