add a property to a class in python

To add a property to a class in Python, you can use the @property decorator to define a getter method for the property. You can also define a setter method using the @<property name>.setter decorator.

Here's an example:

main.py
class Person:
    def __init__(self, name):
        self._name = name
        
    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, new_name):
        self._name = new_name
221 chars
12 lines

In this example, we define a Person class with a private _name attribute. We use the @property decorator to define a getter method for the name property, and the @name.setter decorator to define a setter method for the name property.

Now we can create a Person object and set or get the name property:

main.py
>>> person = Person("John")
>>> person.name
"John"
>>> person.name = "Jane"
>>> person.name
"Jane"
99 chars
7 lines

Note that the getter and setter methods are named after the name of the property, and the setter method has the @<property name>.setter decorator.

gistlibby LogSnag