Junior — Middle
How can you access the attributes of an object declared in a class in Python?
sobes.tech AI
Answer from AI
In Python, access to the attributes of an object declared in a class is done through dot notation. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person('Ivan', 30)
print(p.name) # Outputs: Ivan
print(p.age) # Outputs: 30
Here, p.name and p.age are accesses to the attributes of the object p. You can also use the functions getattr() and setattr() for dynamic access:
print(getattr(p, 'name')) # Ivan
setattr(p, 'age', 31)
print(p.age) # 31