Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Getters and setters

So I learnt that @property is a decorator to indicate a method that accesses an attribute and @propertyname.setter is the decorator to indicate a method that allows us to assign something to the attribute.

example

@property def Name(self) return self.name

@Name.setter def NameSetter(self, value) self.name = value

1) Does the @property create a new attribute Name if it wasn't already explicitely declared in the class?

2) If I only want a setter and no getter, should I start the getter method name with dunder? It seems to me that a setter method always needs a getter method.

1 Answer

Steven Parker
Steven Parker
229,786 Points

A property should always have a unique name that is not used by another attribute in the class.

And while getters and setters often go together, they don't need to. You can have a setter by itself and you would still use the property name when defining it the same way.