Skip to content

Instantly share code, notes, and snippets.

@FerdinaKusumah
Created October 5, 2021 06:48
Show Gist options
  • Save FerdinaKusumah/ca5cba39e7ffb488afa7605295e99f2b to your computer and use it in GitHub Desktop.
Save FerdinaKusumah/ca5cba39e7ffb488afa7605295e99f2b to your computer and use it in GitHub Desktop.
Dynamic attributes 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 get_address(self):
return self.address
if __name__ == "__main__":
# initialize student class
s = Student()
# assign value to it
s.name = "Bob"
s.age = 19
s.hobby = "swimming"
s.address = "Jalan jalan mulu"
# print value inside class as dictionary
# it will print {'age': 19, 'name': 'Bob', 'hobby': 'swimming', 'address': 'Jalan jalan mulu'}
print(s.__dict__)
# print current value in class
print(s.get_name) # Bob
print(s.get_age) # 19
print(s.get_hobby) # swimming
print(s.get_address) # Jalan jalan mulu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment