add a public property to a class in python

To add a public property to a class in python, you can use the @property decorator and define getter and setter methods for that property.

Here's an example:

main.py
class MyClass:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, new_value):
        self._value = new_value
220 chars
12 lines

In this example, we define a MyClass with a private _value attribute. Then, we use the @property decorator to define the getter method value() and the @value.setter decorator to define the setter method value(new_value).

Now, we can access the value property of a MyClass instance like this:

main.py
obj = MyClass(10)
print(obj.value)  # Output: 10
obj.value = 20
print(obj.value)  # Output: 20
95 chars
5 lines

Note that while _value is private, value is publicly accessible and behaves like a regular attribute.

gistlibby LogSnag