Reputation: 679
Let's say I have a class of Person
and I want to assign new properties for each instance but I also want to keep track of said new properties, something like:
class Person:
def __init__(self, **kwargs):
self.props = {}
for arg in kwargs:
self.props[arg] = self.__dict__[arg] = kwargs[arg]
But for example, the following code would show why this doesn't gets me what I need:
person = Person(name='Tomer')
person.props['name'] = 'Michael'
print(person.name)
# >> 'Tomer'
How can I keep a reference to the added attributes with the option to edit their source?
Upvotes: 1
Views: 812
Reputation: 4666
The __dict__
object is the dictionary object of your class or instance. There is no need to directly manipulate that, because the class can handle setting the attributes itself. You can simply set the attributes directly without the need of an intermediate props
:
class Person:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
Then you can just say:
person = Person(name='Tomer')
print(person.name) # output: "Tomer"
person.name = 'Michael'
print(person.name) # output: "Michael"
I'm not sure if that is what you want, though.
Upvotes: 1
Reputation: 72755
class P(dict):
def __init__(self, *k, **kwargs):
self.__dict__ = self
super().__init__(*k, **kwargs)
p = P(name = "me", age = 40)
>>> p['name'] == p.name == "me"
True
etc.
Upvotes: 1
Reputation: 679
Got my answer, you can just set the __getattr__
function on the Person
class which would execute when access to a variable that is not in the class and parent class is accessed.
Upvotes: 1