
class MyClass: |
my_attribute = 42 |
def my_method(self, arg): |
print(f"This is my_method with arg {arg}.") |
obj = MyClass() |
print(hasattr(obj, "my_method")) |
print(hasattr(obj, "my_attribute")) |
# Output: |
# True |
# True |
# Using getattr to access an attribute |
print(getattr(obj, "my_attribute")) |
# Output: |
# 42 |
# Using setattr to add an attribute |
setattr(obj, "new_attribute", "hello") |
print(obj.new_attribute) |
# Output: |
# hello |
# Using delattr to delete an attribute |
delattr(obj, "new_attribute") |
print(hasattr(obj, "new_attribute")) |
# Output: |
# False |
# Dynamically creating a class |
MyDynamicClass = type("MyDynamicClass", (), {"my_attribute": 42, "my_method": lambda self, arg: print(f"This is my_method with arg {arg}.")}) |
obj2 = MyDynamicClass() |
print(obj2.my_attribute) |
obj2.my_method("test") |
# Output: |
# 42 |
# This is my_method with arg test. |



