xxxxxxxxxx
class Student:
name = 'John'
student = Student()
# Set 'age' attribute to 23
setattr(student, 'age', 23)
print('Student name: ', student.name)
print('Student age: ', student.age)
# Output
# Student name: John
# Student age: 23
xxxxxxxxxx
# Per https://www.w3schools.com/python/ref_func_setattr.asp,
# the setattr() function sets the value of the specified attribute of the specified object.
# Here is a sample code from https://www.w3schools.com/python/trypython.asp?filename=demo_ref_setattr
class Person:
name = "John"
age = 36
country = "Norway"
setattr(Person, 'age', 40)
# The age property will now have the value: 40
x = getattr(Person, 'age')
print(x)
xxxxxxxxxx
#Use the setattr Function
class Example:
a = "Pynerds"
#set a variable attribute to the class
setattr(Example, "b", "Python")
setattr(Example, "c", "Django")
def example_method():
print("Hello, World!")
#set a method attribute to the class
setattr(Example, "example_method", example_method)
print(Example.a)
print(Example.b)
print(Example.c)
Example.example_method()
xxxxxxxxxx
#Use the setattr Function
class Example:
a = "Pynerds"
#set a variable attribute to the class
setattr(Example, "b", "Python")
setattr(Example, "c", "Django")
def example_method():
print("Hello, World!")
#set a method attribute to the class
setattr(Example, "example_method", example_method)
print(Example.a)
print(Example.b)
print(Example.c)
Example.example_method()
xxxxxxxxxx
#Use the setattr Function
class Example:
a = "Pynerds"
#set a variable attribute to the class
setattr(Example, "b", "Python")
setattr(Example, "c", "Django")
def example_method():
print("Hello, World!")
#set a method attribute to the class
setattr(Example, "example_method", example_method)
print(Example.a)
print(Example.b)
print(Example.c)
Example.example_method()