What are class attributes?

Class attributes are variables that are shared among all instances (objects) of a class. They are defined within the class but outside of any instance methods. Class attributes are typically used to store data that is common to all instances of the class.

Here's an example to illustrate class attributes:

class Dog:
    species = "Canis lupus familiaris"  # Class attribute

    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age    # Instance attribute

# Creating instances of the Dog class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# Accessing class attribute
print(dog1.species)  # Output: Canis lupus familiaris
print(dog2.species)  # Output: Canis lupus familiaris

# Accessing instance attributes
print(dog1.name)  # Output: Buddy
print(dog2.age)   # Output: 5

In this example, species is a class attribute that is shared by all instances of the Dog class, while name and age are instance attributes that can have different values for each object.

0 Comments

no data
Be the first to share your comment!