views:

460

answers:

4

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"])
+3  A: 

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.

Alex Martelli
I was just giving an example, but you are right, I would want to copy the list first before changing it ;)
Jiaaro
+3  A: 

Have you tried this?

fields = lgrAdminObject.fields + ["albums"]

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

Ber
+2  A: 

If you insist on using class attributes, you can reference the base class directly.

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

A trivial check follows:

>>> class B0:
...     fields = ["title","owner"]
...     
>>> class C1(B0):
...     B0.fields.extend(["albums"])
...     
>>> C1.fields
['title', 'owner', 'albums']
>>> B0.fields
['title', 'owner', 'albums']
>>>

Looks like the base attribute is modified as well, probably not what you were looking for. Look into defining some executable method (__init__(), maybe?).

Or (better?) follow @Alex Martelli's suggestion and copy the base attribute:

>>> class B0:
...     fields = ["title","owner"]
... 
>>> class C1(B0):
...     fields = B0.fields[:]
...     fields.extend(["albums"])
...     
>>> C1.fields
['title', 'owner', 'albums']
>>> B0.fields
['title', 'owner']
>>>
gimel
A: 

Also, note that when you have a list as a class attribute, it belongs to the class, not the instances. So if you modify it, it will change for all instances. It's probably better to use a tuple instead, unless you intend to modify it with this effect (and then you should document that clearly, because that is a common cause of confusion).

Lennart Regebro