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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With