Object-oriented and process-oriented in python

Keywords: PHP Python Attribute Programming

Object-Oriented and Process-Oriented

1. What is process-oriented

The core is the word process: process-oriented is a kind of pipeline workflow, which is what to do first and what to do first.

2. What is Object-Oriented

The core is the word "object": a programming idea, God's thinking, everything is an object, responsible for scheduling and control in programming.

    

The Advantages and Disadvantages of Object-Oriented and Process-Oriented

Process-oriented:

Advantages: Strong logic of the program; Simplification of complex problems

Disadvantages: poor maintenance; poor functional expansion

Object-oriented:

Advantages: strong functional expansibility, high maintainability and reusability

Disadvantage: Code complexity increases

4. How to create classes and objects

2.0 grammar

    class  A:

      def __init__(self,name,age):

        self.name = naem

        self.age = age

The a1 = A() type plus parentheses automatically triggers the _init_() method at the initialization stage to create an empty object. Only when the value is passed will the method of _init_() function be triggered again. The process of initializing the object and assigning the value > to produce the object is realized.

   

2.1 How to set properties

The attributes under the class are created according to the requirements of the object, and what attributes do the object need to set?

2.2 Attribute Search Order

Priority: Find Yourself > Category > Parent Category

2.3 Object Initialization Method

    

2.4 Binding and non-binding methods

1. The method of binding to an object, which has initialization time 2. The method of function in a class is to bind to an object by default. It will pass the instantiated object as the first parameter of the function by default and receive it by variable name self.

2. When we need to call a class usage function, the function under the @classmethod decorator automatically passes <class> as the first parameter, which is the function bound to the class by defau lt.

3. @static static method is bound to whoever does not need to pass parameters

  

2. Three Object-Oriented Characteristics

Inheritance

2. Packaging

3. Polymorphism

 

Inheritance

1. What is inheritance?

Definition: What is the relationship described? What is described in the program is the relationship between classes. There is a certain relationship between them.

super () method

If you inherit an existing class and you override init, you must call the init of the parent class first.

Attributes and methods of accessing parent classes by subclasses: First find your own > class > parent class > object is the base class of all classes

2. Why to use inheritance:

Reason: Subclasses can use all the unpackaged attributes and methods of the parent class to improve code reuse without rewriting the initial assignment of the _init_ method materialization in subclasses

  

3. Inheritance Grammar

If a inherits b, then B is the parent of a, and a can inherit all the attributes of the parent class B and the methods and data attributes that are not encapsulated

4. First abstract in inheritance

In fact, it is a process of extracting the same attributes and sharing methods, which is abstract.

  

class A:
    name = 'alice'

    def __init__(self, name, age):
        self.name = name
        self.age = age

class B(A):
    pass
a1 = A()

 

5. What combination has nothing to do with it

Definition: Treating an object as an attribute of another object does not have any relationship with inheritance.

To use its properties and functions

class Date:
    def __init__(self,year, month,day):
        self.year = year
        self.month = month
        self.day = day
    def info(self):
        print('I am date Functions in')

class Teacher:
    def __init__(self,name, age, num,date):
        self.name = name
        self.age = age
        self.num = num
        self.date = date

    def change_score(self):
        print('Modify the score')


class Student:
    def __init__(self,name,date):
        self.date = date
        self.name = name

    def choice(self):
        print('Choice')


d1 = Date(2019,7,27)
print(d1.year)
print(d1.month)
print(d1.day)
# s1 = Student('koko')  # koko couldn't adjust his score or his date if he wanted to change it.

s2 = Student('koko',d1)
print(s2.date.year)
print(s2.date.month)
print(s2.date.day)
s2.date.info()  # Intra-class functions perform calls directly, do not need parentheses to print, and do not return values. None Unless you set it up return value

t1 = Teacher('lire',18,10,d1)
print(t1.date.year)
t1.date.info()

>>>>>

2019
7
27
2019
7
27
I am date Functions in
2019
I am date Functions in

 

 

6. Derivation

When a subclass inherits parent methods and attributes, it redefines new attributes and methods.

Priority is given to using your own class when using it, and you will not use your own parent class if you do not have one.

7. Coverage

When inheriting a parent class, a subclass has its own redefined attributes and method's own attributes, which are identical to the name of the parent class.

9. New and Classical Classes

New Class: The default inheritance of the object class is called the new class

The default in python is that new classes have no classical classes

Classic Class: Classic Class used in Classic Class Python 2 that does not inherit the object class

10. rhombic inheritance mro: C3 algorithm

Classes in search = order will follow mro search, depth first, if several classes are encountered in the search process and inherit a parent class breadth first at the same time

  

II. Packaging

2.1 What is encapsulation

  

1. Definition: hide ugly, complex, privacy details inside and provide a simple use interface to the outside.
Hide internal implementations from the outside and provide a simple interface for function access

2. Purpose:
    1. To ensure data security
    2. Hiding implementation details to the outside world, isolation complexity () is the main reason for isolation complexity.

3. When to use:
    1. When there is some data that you don't want to be used directly by the outside world
    2. When some functions do not want to be used by the outside world

4. Grammar: _ attribute names assign initial values in serialization
 
##### Characteristics of encapsulated content:

1. The outside world is not directly accessible

2. Internal queries can still be invoked by setting functions

## 

 

2.3 encapsulated grammar

class Person:
    def __init__(self, name, age, id_number):
        self.name = name
        self.age = age
        self.__id_number = id_number

 

2.4 Principle of encapsulation: Variables encapsulate our hidden self._name into parent class name variable name when assigning initial values to class materialized objects, which means that it is impossible to access his name with object point name again without calling functions.

 

2.5 Access to Private Attributes: Decorators

  

class Person:
    def __init__(self, name, age, id_number):
        self.name = name
        self.age = age
        self.__id_number = id_number
    @property
    def id_number(self):
        return self.__id_number


p1 = Person('coco', 18, 6666)  # Class Generation Object Initial Recognition Assignment Stores Generated Variables in Namespace so that the binding relationship is determined at the time of initialization
                                 # Encapsulation is the encapsulation of hidden genera

Methods:

1. If you want to access the encapsulated attributes, you can define a function under the attributes of the class and return our encapsulated variable names in the function.

   def id_number(self):
        return self.__id_number

2. Adding @property is the same internal code that must be designed to return the data attributes we need to find

Why use @property

# How to Value, Modify and Delete Attributes for Write Encapsulation


class Iphone:
    def __init__(self,kind, price, red):
        self.__kind = kind
        self.__price = price
        self.__red = red

    # Method red, kind, price
    @property
    def red(self):
        return self.__red
    @red.setter
    def red(self,new_color):
       self.__red = new_color


IP = Iphone('Apple', 4888, 'gules')
# print(IP.red())  # Functions have direct access to internally encapsulated things
# print(IP.__red)  # What if there is no way to get it now? >>>Yes?@Property Ducks are like that. IP.red Camouflage as an object point.red

print(IP.red)

IP.red = 'green'
# print(IP.red)
# print(IP.red)
# print(IP.red)
# print(IP.red)

print(IP.red)  # The green clip decorator is designed to allow you to modify and view internal attributes and invocation methods externally.

The reason is that the design is to design the function name to be exactly the same as the variable name we want to access > > > add @property, and then we can directly form the object point function.

In fact, it is to disguise the value of the memory space to which the variable name of the direct object points. The actual situation is that we provide an interface to the outside world and encapsulate the details of our internal implementation.

 

How to access privatized functions: encapsulated functions

# Purpose not to allow external modification of internal attributes and methods


class Person:
    def __init__(self, name, age, id_number):
        self.name = name
        self.age = age
        self.__id_number = id_number

    @property
    def id_number(self):
        return self.__id_number

    def __run(self):  # How to access functions privatized by encapsulation  __run Substantial deformation is as follows:_Class name to which it belongs__Function name
        print('running')
        print('Password 009')

    def bar(self,y):  # It's so simple to define a function inside a function. The result of his return is that the encapsulated function can get the contents of the code execution inside.
        if y < 100:
            return self.__run()

>>>>

It's so simple to define a function inside a function. The result of his return is that the encapsulated function can get the contents of the code execution inside.
Packaging principle:
 _ run is essentially transformed into: _____________ function name
 Principle of p1. _Person_ run () Privatization
p1.bar(70) # sets the return value by defining a new function access

2.6. Encapsulating Computing Properties

# 1. Calculate the area of a element or rectangle
# Calculate the area of a element or rectangle

class Radio:
    def __init__(self,r=10):
        self.__r = r

    #Calculating perimeter
    @property
    def r(self):
        return self.__r
    @r.setter

    def r(self, new_r):
        self.__r = new_r
    #Calculated area

    def ares(self):
        return 3.14*self.__r**2


r1 = Radio()
res1 = r1.ares()
print(res1)
r1.r = 20
# r2 = Radio(20)  # Internally, we are limited to death, so there is no way to change what to do.
res = r1.ares()
print(res)
# Now I want to change my value from outside.
# print(r1.R())
# print(r2.R())
print(Radio.__dict__)

Computing BMI

# Practice: Define a class called person
# Including three attributes of height and weight   BMI
# BMI The weight of the body should be calculated by calculating the value. / Square of height

class BaseClass:
    def __init__(self, high, weight,):
        self.high = high
        self.weight = weight

    def BMI(self):
        # Formula: BMI = weight(KG)/height(m)Square
        return self.weight/self.high**2

#  Materialized object


person1 = BaseClass(1.65, 62)
print(person1.BMI())

"""
//When BMI index was 18.5-23.9, it was normal.

//BMI numerical criteria for adults:
//Too light: below 18.5 normal: 18.5-23.9

//Overweight: 24-27 Obesity: 28-32
"""

 

2.7 Duck Type

Interface

What is the interface: If the USB interface provides a set of unified standard protocols, as long as you follow the interface protocol established by use, your device can be connected to computer input operations by using the function of usd.

# Interface: USB Provides a unified set of standards, also known as protocols, as long as you follow this set of protocols, your device can be connected to the computer to use, whether you are a mouse or keyboard can be recognized to operate the computer.
class Mouse:
    def open(self):
        print('Mouse opens computer')

    def close(self):
        print('The mouse is off.')

    def read(self):
        print('Mouse Acquisition Close Cursor')

    def write(self):
        print('Mouse does not support writing')


def pc(usb_server):
    usb_server.open()
    usb_server.close()
    usb_server.write()
    usb_server.close()

m = Mouse()
pc(m)  # This is an external function with parentheses to pass parameters.

class KeyBord:
    def open(self):
        print('Keyboard open...')

    def close(self):
        print('The keyboard is off...')

    def read(self):
        print('Get the key character.')

    def write(self):
        print('Keyboard Write Information')

# Duck type attributes are similar, the method is similar, so it is called duck type.
k= KeyBord()
pc(k)


class Udisk:
    def open(self):
        print('u Disk started')

    def close(self):
        print('U Disk closure')

    def read(self):
        print('Readout data')

    def write(self):
        print('Write data')

u = Udisk()
pc(u)

 

Abstract classes

Definition: abc abstract class is that there is no function body code in the function body, no function body definition function, no function content

# Mandatory functions of subclasses are identical to those of parent classes, but we can define and add abstract classes of other functional codes within subclasses according to requirements, but a unified set of interfaces can use my stuff, but must follow my protocol standards.

# Interface and image extraction classes:
# What's an interface: It's a set of protocol specifications that specify what functions subclasses should have.
# Abstract classes are used to enforce that word classes must be implemented in accordance with the protocol. python Not respected

# Duck Type: It allows multiple objects of different classes to have the same attributes and methods for users.,It can be changeable and changeable.,Easy to use all kinds of objects

"""
abc
//Definition of abstract classes: Classes contain methods without functions
"""
import abc


class AClass(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def eat(self):
        pass

    @abc.abstractmethod
    def eat1(self):
        pass


class Gt(AClass):
    def eat(self):
        print('I am eating....')

    def eat1(self):
        print('111111')
        while True:
            choice = input('Input instruction calling this function:').strip()
            if choice == '123456':
                print('yes')
                break
            else:
                print('false')
                continue


b = Gt()  # Can't use abstract method eat1 Deserializing abstract classes Gt

b.eat1()

 

    

Duck type

A class looks like a duck and walks like a duck.

However, python does not advocate the grammatical rules that restrict us. Instead, we can design duck types that allow multiple objects of different classes to have the same attributes and methods.

For users, it means that they can respond to changes with unchangeability. It's easy to use all kinds of objects.

3. Polymorphism
 

Posted by mantona on Sat, 27 Jul 2019 05:50:04 -0700