Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use attributes vs. when to use properties in python?

Tags:

python

Just a quick question, I'm having a little difficulty understanding where to use properties vs. where use to plain old attributes. The distinction to me is a bit blurry. Any resources on the subject would be superb, thank you!

like image 276
Michael Avatar asked Jun 10 '12 10:06

Michael


People also ask

When should I use property Python?

Python's property() is the Pythonic way to avoid formal getter and setter methods in your code. This function allows you to turn class attributes into properties or managed attributes. Since property() is a built-in function, you can use it without importing anything.

What is difference between attributes and properties?

An attribute is a quality or character ascribed to or considered to belong to, or be inherent in, a person or thing. A property is a quality or characteristic belonging to a person or thing, with its original use implying ownership, and also either being essential or special.

What is the difference between attributes and functions in Python?

A variable stored in an instance or class is called an attribute. A function stored in an instance or class is called a method.


1 Answers

Properties are more flexible than attributes, since you can define functions that describe what is supposed to happen when setting, getting or deleting them. If you don't need this additional flexibility, use attributes – they are easier to declare and faster.

In languages like Java, it is usually recommended to always write getters and setters, in order to have the option to replace these functions with more complex versions in the future. This is not necessary in Python, since the client code syntax to access attributes and properties is the same, so you can always choose to use properties later on, without breaking backwards compatibilty.

like image 199
Sven Marnach Avatar answered Oct 06 '22 16:10

Sven Marnach