DEV Community

Spencer Adler
Spencer Adler

Posted on

Properties and attributes in Python

When writing code in Python there are many different functions you can write. In these functions you can create attributes and property.

The definition of attributes are variables that belong to an object. The definition of properties are attributes that are controlled by methods.

An example of attributes and properties are below.

Attributes:

class Traveler:
    some attribute= "All members of this class will have this attribute."
    def __init__(self, name):
         self.name = name
Enter fullscreen mode Exit fullscreen mode

name is an attribute of the traveler class. Since it is inside the function it is instance attribute.

Some attribute will be same for all the travelers while the name can change for each traveler.

The traveler class can have many attributes like age, height etc... These attributes provide more information about the class. Similar to props in React.

Properties:
In adding to the code above you can get and set the name using some parameters. Then you would have a property for the name.

def get_name(self):
    return self._name

def set_name(self, name):
    if type(name)==str and len(name) > 0:
         self._name = name
    else:
         print("Name needs to be a string and longer than 0 characters.")
Enter fullscreen mode Exit fullscreen mode

name = property(get_name,set_name)

get_name gets the name and then set name sets the name with the parameters in the code. When the name is input not following those parameters the console prints out an error message on what the requirements are. Then the property calls get_name and set_name when the property is called. See below for a way to call the property for name.

some_traveler = Traveler(name="Spencer")

name equaling Spencer is passed into the Traveler class and the property name is called. It gets the name and then sets it. Since it is a string and greater than 0 characters it is able to set it without an error message. Now when some_traveler.name is called it will be Spencer.

Top comments (0)