Skip to content

Instantly share code, notes, and snippets.

@FerdinaKusumah
Last active October 5, 2021 12:45
Show Gist options
  • Save FerdinaKusumah/1494bf234473272624d3f684552d7365 to your computer and use it in GitHub Desktop.
Save FerdinaKusumah/1494bf234473272624d3f684552d7365 to your computer and use it in GitHub Desktop.
Manual Assign Attributes Values
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__":
external_source = [{"name": "bob", "age": 19, "hobby": "swimming"}]
# store student class inside temporary variable
tmp = []
for data in external_source:
# initialize student class
s = Student()
# assign value to it
s.name = data.get("name", None)
s.age = data.get("age", None)
s.hobby = data.get("hobby", None)
s.address = data.get("address", None)
# ... more assign value here if this class have many attributes
tmp.append(s)
# print value inside class as dictionary
for s in tmp:
# print current value in class
print(s.get_name) # Bob
print(s.get_age) # 19
print(s.get_hobby) # swimming
print(s.is_adult) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment