Python Classes/Objects

Python Classes and Objects

Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods.

To create objects, we use a Class. A Class is like an object constructor, or a "blueprint" for creating objects.


1. Create a Class

To create a class in Python, use the keyword class.

Create a Class

class MyClass:
  x = 5

print(MyClass)


2. Create an Object

Now we can use the class named MyClass to create objects. An object is a specific instance of a class.

Create an Object

// Create an object named p1, and print the value of x:
class MyClass:
  x = 5

p1 = MyClass() print(p1.x)


3. Creating Multiple Objects

You can create as many objects as you want from a single class. Each object is independent of the others.

Multiple Instances

class Car:
  wheels = 4

// Create two separate Car objects car1 = Car() car2 = Car()

print("Car 1 wheels:", car1.wheels) print("Car 2 wheels:", car2.wheels)


The pass Statement

Class definitions cannot be empty. If you need to create a class with no content (perhaps as a placeholder for future code), use the pass statement to avoid getting an error.

class EmptyClass:
  pass

Exercise

?

Which keyword is used to create a class in Python?