Skip to content

Instantly share code, notes, and snippets.

@FerdinaKusumah
Created October 5, 2021 12:56
Show Gist options
  • Save FerdinaKusumah/8d91b463658e9664ecf91992b3d3045f to your computer and use it in GitHub Desktop.
Save FerdinaKusumah/8d91b463658e9664ecf91992b3d3045f to your computer and use it in GitHub Desktop.
class Student:
name: str = "foo"
hobby: str = "bar"
def __init__(self, age: int = 0):
self.age = age
@property
def get_name(self):
return self.name
@property
def get_hobby(self):
return self.hobby
@property
def get_age(self):
return self.age
@property
def is_adult(self):
return self.age > 17
if __name__ == "__main__":
# let say we get data from external source
external_source = [
{"name": "Bob", "age": 19, "hobby": "swimming"},
{"name": "John", "age": 18, "hobby": "play football"},
{"name": "Alex", "age": 21, "hobby": "play badminton"},
]
# prepare for temporary value
tmp = []
for data in external_source:
# define class
s = Student()
# dynamically set attributes based on external source
_ = [setattr(s, i, data[i]) for i in data.keys()]
tmp.append(s)
# now print all value from class
for student in tmp:
# value will print like this
"""
Bob is 19 years old, and hobby is swimming
John is 18 years old, and hobby is play football
Alex is 21 years old, and hobby is play badminton
"""
print("{} is {} years old, and hobby is {}".format(
student.get_name,
student.get_age,
student.get_hobby))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment