Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class attribute inheritance

I am trying to save myself a bit of typing by writing the following code, but it seems I can't do this:

class lgrAdminObject(admin.ModelAdmin):
    fields = ["title","owner"]
    list_display = ["title","origin","approved", "sendToFrames"]

class Photos(lgrAdminObject):
    fields.extend(["albums"])

why doesn't that work? Also since they're not functions, I can't do the super trick

fields = super(Photos, self).fields
fields.extend(["albums"])
like image 949
Jiaaro Avatar asked Feb 26 '26 19:02

Jiaaro


2 Answers

Inheritance applies after the class's body executes. In the class body, you can use lgrAdminObject.fields -- you sure you want to alter the superclass's attribute rather than making a copy of it first, though? Seems peculiar... I'd start with a copy:

class Photos(lgrAdminObject):
    fields = list(lgrAdminObject.fields)

before continuing with alterations.

like image 123
Alex Martelli Avatar answered Mar 01 '26 08:03

Alex Martelli


Have you tried this?

fields = lgrAdminObject.fields + ["albums"]

You need to create a new class attribute, not extend the one from the parent class.

like image 40
Ber Avatar answered Mar 01 '26 09:03

Ber