8000 using setattr and getattr · ammarlodhi255/python-src@e4ffe65 · GitHub
[go: up one dir, main page]

Skip to content

Commit e4ffe65

Browse files
committed
< 8000 /div>
using setattr and getattr
1 parent eec26bf commit e4ffe65

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

tips_in_python/setattr_and_getattr.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Person:
2+
pass
3+
4+
5+
person = Person()
6+
7+
attr_name = 'first_name'
8+
attr_value = 'Ammar'
9+
10+
# We can't just do this:
11+
# person.attr_name = attr_value
12+
13+
# Solution:
14+
setattr(person, attr_name, attr_value)
15+
16+
print(person.first_name)
17+
18+
# If you want to access the value of a particular attribute, give its name:
19+
# We can't just that: print(person.attr_name)
20+
21+
# Solution:
22+
value = getattr(person, attr_name)
23+
24+
print(value)
25+
26+
27+
# Let us now create a another instance of Person and dynamically assign it attributes with values
28+
person_info = {
29+
'first': 'Ammar',
30+
'last': 'Ahmed',
31+
'field_of_study': 'CompSci'
32+
}
33+
34+
person = Person()
35+
36+
for key, value in person_info.items():
37+
setattr(person, key, value)
38+
39+
for key in person_info.keys():
40+
print(f'{key}: {getattr(person, key)}')

0 commit comments

Comments
 (0)
0