Properties and attributes in Python

WBOY
Release: 2024-07-18 09:02:41
Original
427 people have browsed it

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
Copy after login

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.")
Copy after login

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.

The above is the detailed content of Properties and attributes in Python. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!