Codecademy Logo

Python Object-Oriented Programming with AI

Related learning

  • Learn Python programming with AI tools. This course takes you from fundamentals to best practices using Codex CLI for serious development.
    • Includes 4 Courses
    • With Certificate
    • Beginner Friendly.
      7 hours

Python class

In Python, a class is a template for a data type. A class can be defined using the class keyword.

# Defining a class
class Animal:
def __init__(self, name, number_of_legs):
self.name = name
self.number_of_legs = number_of_legs

Instantiate Python Class

In Python, a class needs to be instantiated before use.

As an analogy, a class can be thought of as a blueprint (Car), and an instance is an actual implementation of the blueprint (Ferrari).

class Car:
"This is an empty class"
pass
# Class Instantiation
ferrari = Car()

Python class methods

In Python, methods are functions that are defined as part of a class. It is common practice that the first argument of any method that is part of a class is the actual object calling the method. This argument is usually called self.

# Dog class
class Dog:
# Method of the class
def bark(self):
print("Ham-Ham")
# Create a new instance
charlie = Dog()
# Call the method
charlie.bark()
# This will output "Ham-Ham"

Python Class Variables

In Python, class variables are defined outside of all methods and have the same value for every instance of the class.

Class variables are accessed with the instance.variable or class_name.variable syntaxes.

class my_class:
class_variable = "I am a Class Variable!"
x = my_class()
y = my_class()
print(x.class_variable) #I am a Class Variable!
print(y.class_variable) #I am a Class Variable!

Python init method

In Python, the .__init__() method is used to initialize a newly created object. It is called every time the class is instantiated.

class Animal:
def __init__(self, voice):
self.voice = voice
# When a class instance is created, the instance variable
# 'voice' is created and set to the input value.
cat = Animal('Meow')
print(cat.voice) # Output: Meow
dog = Animal('Woof')
print(dog.voice) # Output: Woof

Learn more on Codecademy

  • Learn Python programming with AI tools. This course takes you from fundamentals to best practices using Codex CLI for serious development.
    • Includes 4 Courses
    • With Certificate
    • Beginner Friendly.
      7 hours