Sobes.tech
Junior — Middle

What are the ways to access object properties without using the get method?

sobes.tech AI

Answer from AI

In Python, access to an object's properties can be obtained directly through dot notation, without using the get method. For example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person('Ivan', 30)
print(p.name)  # direct access to property

You can also use the getattr() function, which allows you to get the value of a property by its name as a string:

print(getattr(p, 'age'))  # 30

Thus, the main ways to access object properties without the get method are:

  • Direct access via object.property
  • Using getattr(object, 'property_name')

If you need to control access or compute the value, you can use the @property decorator, but this is no longer direct access to the attribute, rather a call to a method formatted as a property.