Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the meta attributes of a superclass in Python?

Tags:

python

django

I have some code like this for Django-Tastypie:

class SpecializedResource(ModelResource):
    class Meta:
        authentication = MyCustomAuthentication()

class TestResource(SpecializedResource):
    class Meta:
        # the following style works:
        authentication = SpecializedResource.authentication
        # but the following style does not:
        super(TestResource, meta).authentication

I would like to know what would be the right method of accessing meta attributes of the superclass without hard-coding the name of the superclass.

like image 752
Subhamoy S. Avatar asked Oct 14 '13 14:10

Subhamoy S.


1 Answers

In your example it seems that you are trying to override the attribute of the meta of the super class. Why not use meta inheritance?

class MyCustomAuthentication(Authentication):
    pass

class SpecializedResource(ModelResource):
    class Meta:
        authentication = MyCustomAuthentication()

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        # just inheriting from parent meta
        pass
    print Meta.authentication

Output:

<__main__.MyCustomAuthentication object at 0x6160d10> 

so that the TestResource's meta are inheriting from parent meta (here the authentication attribute).

Finally answering the question:

If you really want to access it (for example to append stuff to a parent list and so on), you can use your example:

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = SpecializedResource.Meta.authentication # works (but hardcoding)

or without hard coding the super class:

class TestResource(SpecializedResource):
    class Meta(SpecializedResource.Meta):
        authentication = TestResource.Meta.authentication # works (because of the inheritance)
like image 141
astreal Avatar answered Nov 19 '22 04:11

astreal