Reputation: 110093
I have an object called a "TemporaryPriceReduction" that tells me information on a product that undergoes a sale. The class looks something like this:
class TPR:
def __init__(self, product_id, territory):
self.product_id = product_id
self.territory = territory
In django models, it allows you to define things outside an init (at least in the specific model that inherits the models.Model
base class:
class TPR(models.Model):
product_id = ...
territory = ...
Basically, I'd like to be able to do this:
class TPR(AbstractClass):
product_id = product_id
territory = territory
How could I build something like an abstract base class so that I can define things outside the init
(like in django) rather than having to write the init?
Upvotes: 0
Views: 247
Reputation: 114230
What you are describing is a feature of plain python, not specifically django.
When you assign self.product_id = ...
in __init__
, you are assigning an attribute in the instance called product_id
.
When you assign product_id = ...
in the class body, you are creating an attribute in the class, TPR.product_id
. Instances of your class will not have such an attribute unless you explicitly assign them. Python attribute lookup works such that instance.product_id
will find missing attributes in the class. That implies that all instances that do not explicitly override product_id
, e.g. in __init__
, share the same object as their product_id
through the class.
The point is that you can define attributes using the syntax you want without doing anything special at all with base classes.
Upvotes: 1