my classes
class Base:
#has no attributes of its own
def __init__(self, params):
for key in params:
if hasattr(self, key):
self[key] = params[key]
def __setitem__(self, key, value):
self[key] = value
class Child(Base):
prop1 = None
prop2 = None
self[key] = value
self.__setitem__
Child()
params = dict(
prop1 = "one",
prop2 = "two"
)
c = Child(params)
c.prop1 #"one"
c.prop2 #"two"
params
Base
Child
dict
Just update the __dict__
of the instance in your __init__
:
class Base:
def __init__(self, params):
for key in params:
if hasattr(type(self), key):
self.__dict__[key] = params[key]
Then:
class Child(Base):
field1 = None
field2 = None
c = Child(dict(field1="one", field2="two", field3="three"))
print(c.field1) # "one"
print(c.field2) # "two"
print(c.field3) # => attr error
Grandchildren will behave:
class GrandChild(Child):
field3 = None
gc = GrandChild(dict(field1="one", field2="two", field3="three"))
print(gc.field1) # "one"
print(gc.field2) # "two"
print(gc.field3) # "three"