kopia lustrzana https://github.com/animator/learn-python
Update classes.md
rodzic
937f62905b
commit
33e3b84876
|
@ -1,4 +1,4 @@
|
|||
**Python Classes and Objects**
|
||||
# Python Classes and Objects
|
||||
|
||||
A class is a user-defined blueprint or prototype from which objects are created. Classes provides a means of bundling for data and functionality. Object is the instance of the class. A class can have any number of objects.
|
||||
|
||||
|
@ -31,7 +31,7 @@ p1 = Person("John", 36)
|
|||
p1.myfunc()
|
||||
**Output :**
|
||||
Hello my name is John.
|
||||
**The __init__() Function**
|
||||
# The __init__() Function
|
||||
All classes have a function called __init__(), which is always executed when the class is being initiated.We use the __init__() function to assign values to object properties.
|
||||
**Example:**
|
||||
class Person:
|
||||
|
@ -40,7 +40,7 @@ class Person:
|
|||
self.age = age
|
||||
p1 = Person("John", 36)
|
||||
Here when we created the p1 object with values "john" and 36 that are assigned to name ,age of __init__ function.
|
||||
**The self Parameter**
|
||||
# The self Parameter
|
||||
The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class.
|
||||
**Example:**
|
||||
class Person:
|
||||
|
@ -55,13 +55,13 @@ p1 = Person("John", 36)
|
|||
p1.myfunc()
|
||||
When we call a method of this object as myobject.method(arg1, arg2), this is automatically
|
||||
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
|
||||
**Concepts of Classes**
|
||||
# Concepts of Classes
|
||||
Main principles of OOPs in Python are abstraction, encapsulation, inheritance, and polymorphism.
|
||||
->Abstraction
|
||||
->Encapsulation
|
||||
->Inheritence
|
||||
->Polymorphism
|
||||
**Abstraction**
|
||||
# Abstraction
|
||||
Data abstraction in Python is a programming concept that hides complex implementation details while
|
||||
exposing only essential information and functionalities to users. In Python, we can achieve data abstraction by using abstract classes and abstract classes can be created using abc (abstract base class) module and abstractmethod of abc module.
|
||||
**Abstract Method:**
|
||||
|
@ -75,29 +75,29 @@ class BaseClass(ABC):
|
|||
**Implementation of Data Abstraction in Python**
|
||||
In the below code, we have implemented data abstraction using abstract class and method. Firstly, we import the required modules or classes from abc library then we create a base class ‘Car’ that inherited from ‘ABC’ class that we have imported. Inside base class we create init function, abstract function and non-abstract functions. To declare abstract function printDetails we use “@abstractmethod” decorator. After that we create child class hatchback and suv. Since, these child classes inherited from abstract class so, we need to write the implementation of all abstract function declared in the base class. We write the implementation of abstract method in both child class. We create an instance of a child class and call the printDetails method. In this way we can achieve the data abstraction.
|
||||
**Example:**
|
||||
# Import required modules
|
||||
**Import required modules**
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
# Create Abstract base class
|
||||
**Create Abstract base class**
|
||||
class Car(ABC):
|
||||
def __init__(self, brand, model, year):
|
||||
self.brand = brand
|
||||
self.model = model
|
||||
self.year = year
|
||||
|
||||
# Create abstract method
|
||||
**Create abstract method**
|
||||
@abstractmethod
|
||||
def printDetails(self):
|
||||
pass
|
||||
|
||||
# Create concrete method
|
||||
**Create concrete method**
|
||||
def accelerate(self):
|
||||
print("speed up ...")
|
||||
|
||||
def break_applied(self):
|
||||
print("Car stop")
|
||||
|
||||
# Create a child class
|
||||
**Create a child class**
|
||||
class Hatchback(Car):
|
||||
|
||||
def printDetails(self):
|
||||
|
@ -108,7 +108,7 @@ def printDetails(self):
|
|||
def Sunroof(self):
|
||||
print("Not having this feature")
|
||||
|
||||
# Create a child class
|
||||
**Create a child class**
|
||||
class Suv(Car):
|
||||
|
||||
def printDetails(self):
|
||||
|
@ -124,12 +124,12 @@ car1 = Hatchback("Maruti", "Alto", "2022");
|
|||
|
||||
car1.printDetails()
|
||||
car1.accelerate()
|
||||
# OUtput
|
||||
**OUtput**
|
||||
Brand: Maruti
|
||||
Model: Alto
|
||||
Year: 2022
|
||||
speed up ...
|
||||
**Encapsulation**
|
||||
# Encapsulation
|
||||
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables.
|
||||
|
||||
A class is an example of encapsulation as it encapsulates all the data that is memberfunctions, variables, etc. The goal of information hiding is to ensure that an object’s state is always valid by controlling access to attributes that are hidden from the outside world.
|
||||
|
@ -137,18 +137,18 @@ A class is an example of encapsulation as it encapsulates all the data that is m
|
|||
class=Methods + Variables
|
||||
Encapsulating the methods and variables in class i.e that methods and variables are related and they are written in a class.Encapsulation reduces the code and one can create any number of objects and use them.
|
||||
|
||||
**Protected Members**
|
||||
# Protected Members
|
||||
Protected members (in C++ and JAVA) are those members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore “_”.
|
||||
**Example:**
|
||||
|
||||
# Creating a base class
|
||||
**Creating a base class**
|
||||
class Base:
|
||||
def __init__(self):
|
||||
|
||||
# Protected member
|
||||
self._a = 2
|
||||
|
||||
# Creating a derived class
|
||||
**Creating a derived class**
|
||||
class Derived(Base):
|
||||
def __init__(self):
|
||||
|
||||
|
@ -167,20 +167,15 @@ class Derived(Base):
|
|||
obj1 = Derived()
|
||||
|
||||
obj2 = Base()
|
||||
|
||||
# Calling protected member
|
||||
# Can be accessed but should not be done due to convention
|
||||
print("Accessing protected member of obj1: ", obj1._a)
|
||||
|
||||
# Accessing the protected variable outside
|
||||
print("Accessing protected member of obj2: ", obj2._a)
|
||||
# output
|
||||
Calling protected member of base class: 2
|
||||
**output**
|
||||
Calling protected member of base class: 2
|
||||
Calling modified protected member outside class: 3
|
||||
Accessing protected member of obj1: 3
|
||||
Accessing protected member of obj2: 2
|
||||
|
||||
**Private Members**
|
||||
# Private Member
|
||||
Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private instance variables that cannot be accessed except inside a class.
|
||||
|
||||
However, to define a private member prefix the member name with double underscore “__”.
|
||||
|
@ -190,24 +185,18 @@ class Base:
|
|||
self.a = "GeeksforGeeks"
|
||||
self.__c = "GeeksforGeeks"
|
||||
|
||||
# Creating a derived class
|
||||
**Creating a derived class**
|
||||
class Derived(Base):
|
||||
def __init__(self):
|
||||
|
||||
# Calling constructor of
|
||||
# Base class
|
||||
Base.__init__(self)
|
||||
print("Calling private member of base class: ")
|
||||
print(self.__c)
|
||||
|
||||
|
||||
# Driver code
|
||||
obj1 = Base()
|
||||
print(obj1.a)
|
||||
# output
|
||||
It will raises error because private members cannot be used outside the class even not for derived classes
|
||||
|
||||
**Inheritence**
|
||||
# Inheritence
|
||||
->Inheritance allows us to define a class that inherits all the methods and properties from another class.
|
||||
|
||||
->Parent class is the class being inherited from, also called base class.
|
||||
|
@ -229,7 +218,7 @@ class Person:
|
|||
|
||||
x = Person("John", "Doe")
|
||||
x.printname()
|
||||
# output
|
||||
**output**
|
||||
John Doe
|
||||
|
||||
**Creating of Child Class**
|
||||
|
@ -237,7 +226,7 @@ x.printname()
|
|||
**Example**
|
||||
class Student(Person):
|
||||
pass
|
||||
**Super Function**
|
||||
# Super Function
|
||||
Python also has a super() function that will make the child class inherit all the methods and properties from its parent:
|
||||
**Example:**
|
||||
class Person:
|
||||
|
@ -254,7 +243,7 @@ class Student(Person):
|
|||
|
||||
x = Student("Mike", "Olsen")
|
||||
x.printname()
|
||||
# output:
|
||||
**output:**
|
||||
Mike Olsen
|
||||
**Types of Inheritances**
|
||||
Types of Inheritance depend upon the number of child and parent classes involved. There are four types of inheritance in Python.
|
||||
|
@ -272,19 +261,19 @@ Single inheritance enables a derived class to inherit properties from a single p
|
|||
V
|
||||
class B
|
||||
**Example**
|
||||
# Base class
|
||||
|
||||
class Parent:
|
||||
def func1(self):
|
||||
print("This function is in parent class.")
|
||||
# Derived class
|
||||
|
||||
class Child(Parent):
|
||||
def func2(self):
|
||||
print("This function is in child class.")
|
||||
# Driver's code
|
||||
|
||||
object = Child()
|
||||
object.func1()
|
||||
object.func2()
|
||||
# output
|
||||
**output**
|
||||
This function is in parent class.
|
||||
This function is in child class.
|
||||
**Multiple Inheritance**
|
||||
|
@ -311,7 +300,7 @@ s1 = Son()
|
|||
s1.fathername = "RAM"
|
||||
s1.mothername = "SITA"
|
||||
s1.parents()
|
||||
# output:
|
||||
**output:**
|
||||
Father : RAM
|
||||
Mother : SITA
|
||||
**Multilevel Inheritance**
|
||||
|
@ -354,16 +343,16 @@ Lal mani
|
|||
Grandfather name : Lal mani
|
||||
Father name : Rampal
|
||||
Son name : Prince
|
||||
**Polymorphism**
|
||||
# Polymorphism
|
||||
The word polymorphism means having many forms. In programming, polymorphism means the same function name (but different signatures) being used for different types. The key difference is the data types and number of arguments used in function.
|
||||
**Example of python built in functions**
|
||||
|
||||
# len() being used for a string
|
||||
#len() being used for a string
|
||||
print(len("geeks"))
|
||||
|
||||
# len() being used for a list
|
||||
#len() being used for a list
|
||||
print(len([10, 20, 30]))
|
||||
# output
|
||||
**output**
|
||||
5
|
||||
3
|
||||
**Polymorphism with class methods:**
|
||||
|
@ -395,7 +384,7 @@ for country in (obj_ind, obj_usa):
|
|||
country.capital()
|
||||
country.language()
|
||||
country.type()
|
||||
# Output:
|
||||
#Output:
|
||||
New Delhi is the capital of India.
|
||||
Hindi is the most widely spoken language of India.
|
||||
India is a developing country.
|
||||
|
@ -432,7 +421,7 @@ obj_spr.flight()
|
|||
|
||||
obj_ost.intro()
|
||||
obj_ost.flight()
|
||||
# ouput:
|
||||
#ouput:
|
||||
There are many types of birds.
|
||||
Most of the birds can fly but some cannot.
|
||||
There are many types of birds.
|
||||
|
|
Ładowanie…
Reference in New Issue