attribute
In Python, an attribute is a value associated with an object that can be accessed using dot notation (object.attribute).
Attributes are defining characteristics or properties of an object and can be data attributes (variables) or method attributes (functions).
Example
Here’s a quick examle of a Dog class with three attributes:
class Dog:
# Class attribute
species = "Canis familiaris"
def __init__(self, name, age):
# Instance attributes
self.name = name
self.age = age
# Create two instances of the Dog class
dog1 = Dog("Buddy", 5)
dog2 = Dog("Milo", 3)
# Access the *class* attribute
print(dog1.species) # Output: Canis familiaris
print(dog2.species) # Output: Canis familiaris
# Access the *instance* attributes
print(dog1.name) # Output: Buddy
print(dog2.name) # Output: Milo
Attributes can be:
-
Class Attributes:
.speciesis a class attribute. It’s shared by all instances of theDogclass. This means thatdog1.speciesanddog2.specieswill both return"Canis familiaris". Class attributes are useful for storing data that should be the same for every instance, like a constant value or a default setting. -
Instance Attributes:
.nameand.ageare instance attributes. They are unique to each instance of the class. So,dog1.nameis"Buddy", anddog2.nameis"Milo".
You can access class attributes using either the class name (Dog.species) or an instance (dog1.species), but it’s more common to use the class name when you don’t need to involve a specific instance.
You can check if an object has an attribute using hasattr(), get attribute values with getattr(), set them with setattr(), and delete them with delattr(). Python’s descriptor protocol allows for fine-grained control over attribute access and modification.
Related Resources
Tutorial
Getters and Setters: Manage Attributes in Python
In this tutorial, you'll learn what getter and setter methods are, how Python properties are preferred over getters and setters when dealing with attribute access and mutation, and when to use getter and setter methods instead of properties in Python.
For additional information on related topics, take a look at the following resources: