Python Classes

Python Class Properties

Class attributes and properties

Python Class Properties

Class properties are attributes that belong to the class or its instances. There are two types: class attributes and instance attributes.

Instance Attributes

Instance attributes belong to a specific instance:

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

p1 = Person("Alice")
p2 = Person("Bob")
print(p1.name)  # Alice
print(p2.name)  # Bob

Class Attributes

Class attributes are shared by all instances:

class Person:
    species = "Homo sapiens"  # Class attribute
    
    def __init__(self, name):
        self.name = name

p1 = Person("Alice")
p2 = Person("Bob")
print(p1.species)  # Homo sapiens
print(p2.species)  # Homo sapiens