Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self Referencing Class Definition in python

Tags:

is there any way to reference a class name from within the class declaration? an example follows:

class Plan(SiloBase):     cost = DataField(int)     start = DataField(System.DateTime)     name = DataField(str)     items = DataCollection(int)     subPlan = ReferenceField(Plan) 

i've got a metaclass that reads this information and does some setup, and the base class implements some common saving stuff. i would love to be able to create recursive definitions like this, but so far in my experimentation i have been unable to get the effect i desire, usually running into a "Plan is not defined" error. I understand what is happening, the name of the class isn't in scope inside the class.

like image 322
pedlar Avatar asked Jun 19 '09 22:06

pedlar


People also ask

What is a self referential class?

Self-referential classes are a special type of classes created specifically for a Linked List and tree-based implementation in C++. To create a self-referential class, declare a data member as a pointer to an object of the same class.

What does self refer to in a class in Python?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.

What is a self referential object?

Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member. In other words, structures pointing to the same type of structures are self-referential in nature.


1 Answers

Try this:

class Plan(SiloBase):     cost = DataField(int)     start = DataField(System.DateTime)     name = DataField(str)     items = DataCollection(int)  Plan.subPlan = ReferenceField(Plan) 

OR use __new__ like this:

class Plan(SiloBase):      def __new__(cls, *args, **kwargs):         cls.cost = DataField(int)         cls.start = DataField(System.DateTime)         cls.name = DataField(str)         cls.items = DataCollection(int)         cls.subPlan = ReferenceField(cls)         return object.__new__(cls, *args, **kwargs) 
like image 75
Evan Fosmark Avatar answered Dec 11 '22 05:12

Evan Fosmark