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: Meowdog = Animal('Woof')print(dog.voice) # Output: Woof
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!
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:
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) 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.
In object-oriented programming, polymorphism is the ability to access the behavior of multiple subclasses through the shared interface of a superclass.
In Python, a class is a template for a data type. A class can be defined using the class
keyword.
# Defining a classclass Animal:def __init__(self, name, number_of_legs):self.name = nameself.number_of_legs = number_of_legs