Ad

Declare Object Of Derived Class Initialising Properties Of Base Class

- 1 answer

Base class-

class Base:
    x = models.CharField(max_length=10)

Derived class-

class Derived(Base):
    ...

How do I declare an object of Derived class which initialises x like given below without adding constructor in Derived class. This syntax gives the error: x is not a member of Derived.

obj = Derived(x='foo')
Ad

Answer

If these are supposed to be Django models, then they should inherit from Model:

class Base(models.Model):
    x = models.CharField(max_length=10)

class Derived(Base):
    pass

With that, the call d = Derived(x='foo') should work.


Note: If you don't want the base class to have its own database table, then you can additionaly use abstract = True in the Meta class.

Ad
source: stackoverflow.com
Ad