Python capture class in class definition

I don't even know how to explain it, so here is the code I'm trying to do.

from couchdb.schema import Document, TextField

class Base(Document):
    type = TextField(default=self.__name__) 
    #self doesn't work, how do I get a reference to Base?

class User(Base):
    pass

#User.type be defined as TextField(default="Test2")

      

The reason I am even trying to do this is I am working on creating a base class for the orm I am using. I want to avoid defining a table name for every model I have. Also knowing what python constraints would help me avoid wasting time trying to do impossible things.

+2


a source to share


2 answers


The class object does not exist yet (yet) while the class body is being executed, so there is no way for the code in the class body to get a reference to it (just as there is usually no way for any code to get a reference to any object that does not exist) ... Test2.__name__

however, already does what you're specifically looking for, so I don't think you need any workaround (like metaclasses or class decorators) for your particular use case.

Edit : For an edited question where you just don't need a name as a string, the class decorator is the easiest way to get around this issue (in Python 2.6 or newer):

def maketype(cls):
    cls.type = TextField(default=cls.__name__)
    return cls 

      



and put @maketype

in front of each class that you want to decorate this way. In Python 2.5 or earlier, you need to say maketype(Base)

after each relevant statement class

.

If you want this function to inherit, you need to define a custom metaclass that performs the same functionality in its methods __init__

or __new__

. Personally, I would recommend not defining custom metaclasses unless they are truly indispensable - instead, I take the simpler decorator approach.

+3


a source


You might want to check another question python super class relection



In your case, Test2 .__ base__ will return the base class test. If that doesn't work, you can use the new style: class Test (object)

0


a source







All Articles