Codecademy Logo

Object-Oriented Programming in Python

C# Polyphormism

Polymorphism is the ability in programming to present the same interface for different underlying forms (data types).

We can break the idea into two related concepts. A programming language supports polymorphism if:

  1. Objects of different types have a common interface (interface in the general meaning, not just a C# interface), and
  2. The objects can maintain functionality unique to their data type
class Novel : Book { public override string Stringify() { return "This is a Novel!; } } class Book { public virtual string Stringify() { return "This is a Book!; } } // In the below code, you’ll see that a Novel and Book object can both be referred to as Books. This is one of their shared interfaces. At the same time, they are different data types with unique functionality. Book bk = new Book(); Book warAndPeace = new Novel(); Console.WriteLine(bk.Stringify()); Console.WriteLine(warAndPeace.Stringify()); // This is a Book! // This is a Novel // Even though bk and warAndPeace are the same type of reference, their behavior is different. Novel overrides the Stringify() method, so all Novel objects (regardless of reference type) will use that method.

Object Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a design paradigm that organizes code into separate objects that interact with each other. OOP has four primary aspects: encapsulation, abstraction, inheritance, and polymorphism. Each plays a role in making a software system adaptable to change.

Polymorphism in OOP

In object-oriented programming, polymorphism is the ability to access the behavior of multiple subclasses through the shared interface of a superclass.

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

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

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!