Reputation: 762
Hi I have 2 classes a Model and Parent Class
ModelMaster:
myvar: string = "one"
def myfun():
# do stuff
Model(ModelMaster):
first: string = "hello"
second: int = 123
Modelmaster contains functions that all models should use and attributes
When using the Model as purely a model I want to get the Model instance including all of its attributes but I dont want to see anything that was inherited from ModelMaster
Is there someway to get, from instance of Model, a copy of that model with just the attributes of that class that has all parent attributes and methods removed.
It seems like there would be something built into python3 to do this, rather than writing this myself
anyone have any ideas?
thanks, Simon
Upvotes: 1
Views: 2108
Reputation: 762
The best solution I found was to use
annotations = self.__annotations__
keys = {}
for annotation in annotations:
name = annotation
type = annotations[annotation]
data = self.__getattribute__(annotation)
keys.append({"name":name, "type":type, "data":data})
this method can exist in any class in the inheritance tree and it will only return the attributes for the top level class
I'm still hoping that someone might come up with a cleaner version but this works for me
Upvotes: 0
Reputation: 106553
You can create a new class with Model.__dict__
passed to the type
constructor, but not Model
's base class:
PureModel = type('PureModel', (), dict(Model.__dict__))
so that:
print(PureModel().first)
outputs:
hello
and that PureModel().myvar
would result in:
AttributeError: 'PureModel' object has no attribute 'myvar'
Upvotes: 3