Python Classes Objects
A class is a blueprint that describes what data and behavior a kind of object should have, and an object is a concrete thing built from that blueprint.
Object-oriented programming lets you bundle related data and the functions that work on that data into a single unit. In Python that unit is defined with a class. Think of a class as the design for a house and an object as an actual house built from it: from one design you can construct many houses, each with its own address and colour, yet all sharing the same layout.
Defining a class and creating an object
You define a class with the class keyword followed by a name, conventionally written in CapWords style. Creating an object, also called an instance, looks like calling the class as if it were a function. The data stored on an object is held in attributes, and the functions defined inside a class are called methods.
A simple class with an attribute and a method
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
buddy = Dog("Buddy")
print(buddy.name) # Buddy
print(buddy.bark()) # Buddy says woof!Instance attributes vs class attributes
An instance attribute belongs to one specific object and is usually set inside __init__ using self. A class attribute is shared by every instance because it is defined directly in the class body. Use class attributes for values that are the same for all objects, such as a species or a fixed rate.
Sharing a value across all instances
class Dog:
species = "Canis familiaris" # shared by every dog
def __init__(self, name):
self.name = name # unique to each dog
a = Dog("Rex")
b = Dog("Fido")
print(a.species, b.species) # Canis familiaris Canis familiaris
print(a.name, b.name) # Rex Fido- Define a class with the class keyword and a CapWords name.
- Create an object by calling the class like a function.
- Access attributes and methods with dot notation, such as obj.name.
- Instance attributes are per-object; class attributes are shared.