python class attribute inheritance


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"]) 



Django-queryset get one object per field=foo

1:



Django URL.py and the index
Inheritance applies after the class's body executes.


Arbitrary number of positional arguments in django inclusion tag?
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...


Django i18n and python locales (and dates)
I'd start with a copy:.
How can I optimize my database queries using my actual django model?
class Photos(lgrAdminObject):     fields = list(lgrAdminObject.fields) 
before continuing with alterations..
Django Admin - Bulk editing data?


Ipython common problems


What is the equivalent of Rail's Testing Routes in Django?

2:


Have you tried this?.
fields = lgrAdminObject.fields + ["albums"] 
You need to create a new class attribute, not extend the one from the parent class..


3:


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'] >>>


4:


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)..



85 out of 100 based on 55 user ratings 505 reviews