attribute
An attribute in Python 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).
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 Attribute:
species
is a class attribute. It is shared by all instances of theDog
class. This means thatdog1.species
anddog2.species
will 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:
name
andage
are instance attributes. They are unique to each instance of the class. So,dog1.name
is"Buddy"
, anddog2.name
is"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
Object-Oriented Programming (OOP) in Python
In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.
For additional information on related topics, take a look at the following resources:
By Dan Bader • Updated Feb. 4, 2025