Skip to content

Instantly share code, notes, and snippets.

@FerdinaKusumah
Created October 5, 2021 12:47
Show Gist options
  • Save FerdinaKusumah/033a4c351866ec244f586f3f8e1612d5 to your computer and use it in GitHub Desktop.
Save FerdinaKusumah/033a4c351866ec244f586f3f8e1612d5 to your computer and use it in GitHub Desktop.
Assign Dynamic Attribute Class
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__":
# declare variable called student age and assign value to it
student_age = 18
student_name = "Bob"
# declare student class
s = Student()
# set dynamic to specified attributes in class
setattr(s, "age", student_age)
setattr(s, "name", student_name)
# now get value from that class
print(s.get_age) # 18
print(s.get_name) # Bob
print(s.get_hobby) # bar
print(s.is_adult) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment