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.py221 chars12 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.py99 chars7 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