Back to course

Defining Classes and Creating Objects

Python Programming: The 0 to Hero Bootcamp

Classes and Objects in Python

Defining a Class

Use the class keyword. Class names should follow the convention of PascalCase (Capitalizing the first letter of every word).

python class Dog: # Class attribute (shared by all instances) species = 'Canis familiaris'

# Method: A function defined inside a class
def bark(self):
    print("Woof! Woof!")
    
# The 'pass' keyword is used when a block is required but contains no code.
# class EmptyClass:
#     pass

Creating Objects (Instantiation)

Creating an object from a class is called instantiation. You call the class name like a function.

python

Creating two different Dog objects (instances)

fido = Dog() buddy = Dog()

fido and buddy are now distinct objects with their own memory space.

print(type(fido)) # Output: <class 'main.Dog'>

Accessing Attributes and Calling Methods

Use the dot operator (.).

python

Accessing the shared class attribute

print(fido.species) # Output: Canis familiaris

Calling a method

buddy.bark() # Output: Woof! Woof!