Skip to content

Commit 81f17f5

Browse files
authored
Add examples for getattr, setattr and hasattr
2 parents e8b20ad + f07f5ae commit 81f17f5

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

23_attr.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class X:
2+
def __init__(self, **kwargs):
3+
for key, value in kwargs.items():
4+
setattr(self, key, value)
5+
6+
def get(self, key):
7+
if hasattr(self, key):
8+
return getattr(self, key)
9+
else:
10+
raise AttributeError(f"No attr: '{key}'")
11+
12+
x = X(first_name="First", last_name="Last")
13+
14+
assert x.get("first_name") == "First"
15+
assert x.get("last_name") == "Last"
16+
try:
17+
x.get("middle_name")
18+
except AttributeError:
19+
print("All OK!")

0 commit comments

Comments
 (0)