3

I have a class that contains a dictionary of properties current_properties, the properties that can be added and their corresponding data types are predefined in valid_properties dictionary:

self.valid_properties = {'name': str, 'number': int, 'point_data': list}
self.current_properties = {'name': 'user_1'}

Now, I want to write a method that initializes every new added property to its corresponding empty value. e.g. number is int, once added, new state should be:

self.current_properties = {'name': 'user_1', 'number': 0}

if I add point_data the new state should be:

self.current_properties = {'name': 'user_1', 'number': 0, 'point_data':[]}

How can I get this done?

1
  • "every new added property" - how do you "add" new properties? Commented Jun 25, 2018 at 12:25

2 Answers 2

4

You can look up the type from valid_properties using whatever key you want to insert, then use () to instantiate an object of that type.

>>> valid_properties = {'name': str, 'number': int, 'point_data': list}
>>> current_properties = {'name': 'user_1'}
>>> current_properties
{'name': 'user_1'}
>>> current_properties['number'] = valid_properties['number']()
>>> current_properties
{'number': 0, 'name': 'user_1'}
Sign up to request clarification or add additional context in comments.

Comments

3

Use:

valid_properties = {'name': str, 'number': int, 'point_data': list}
current_properties = {'name': 'user_1'}

current_properties['number'] = valid_properties['number']()
current_properties['point_data'] = valid_properties['point_data']()

print(current_properties)
# {'name': 'user_1', 'number': 0, 'point_data': []}

How?

>>> k = int()                                               
>>> k                                                       
0                                                           
>>> k = list()                                              
>>> k                                                       
[]

int():

Takes number or string to be converted to integer object, and base of the number as parameters. If no parameters are passed, returns 0.

list():

Takes an iterator as parameter. If no parameters are passed, it creates an empty list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.