day10 object-oriented programming

Keywords: Programming Python Attribute Java

Articles Catalogue

Process-oriented

Procedure-oriented is to analyze the steps needed to solve the problem, and then use functions to implement these steps step by step, one by one when using it.

Advantages and disadvantages:

  • Advantage
    • Processing the problem.
    • So we can decompose and simplify the problem.
  • shortcoming
    • Because process decomposition is nailed to death, large-scale changes are needed to extend the functionality of the program.

Object-oriented

Advantages and disadvantages:

Object-oriented is to decompose the problem transaction into various objects. The object is not built to complete a step, but to describe the behavior of a thing in the whole process of solving the problem.

  • Advantage
    • Ensuring the extensibility of the program
  • shortcoming
    • Compared with process-oriented, it is much more complex than process-oriented.
    • Interactive problem solving methods can not accurately predict the results

Object-oriented programming

oop(object oriented programming)

It is a programming idea. oop regards object as the basic unit of program, and an object contains the function of data and operation data.

In python, all data types can be treated as objects, and we can also customize objects. A function in an object's class is defined, which is called the corresponding method of the object.

demo:

If you want to display the results of a student's information:

  • Face the process
students=[{'name':name,'id':id,'grade':grade}]  #Store a student's information in a dictionary
def find_student(id):
    """Subscripts for returning the required student i"""
i=find_student(id)            #Identify students by id and return list index values
print(student[i]['grade'])    #Return results by key s in the dictionary
  • Face the Object
class student:       #Create a student class
    def __init__(self,name,id,grade):
        self.name=name
        self.id=id
        self.grade=grade
        
    def get_grade():  #The method of get grade
        print(self.grade)
stu1=Student('tom',100,55)        #Create a student object
stu1.get_grade()                  #Call the get_grade() method of student

The function of a class is a template, and we can fill in some attributes that we think must be bound when creating an instance. At this point, through the special "_init_" method, when creating an instance, the relevant properties are bound.

Compared with ordinary functions, the method defined in the class, the first parameter must be self, in addition to the general function is basically the same. (Self refers to an instance)

  • _ init_method
    • Is the initialization method of a class, similar to the C # or Java constructor.
    • No return value
    • After initializing the class with this method, the attributes of the instance can be accessed directly through the self parameter.

Two functions of classes

  • Attribute Reference
    • "Class name. Attribute name"
  • instantiation
    • The class name with a bracket is instantiated and the "_init_" function is called directly back to initialize each property of the object.

Special class attributes

  • . _name_Returns the name of the class
  • Document string of. _doc_class
  • The first parent of the. _base_class
  • Tuples of. _bases_class consisting of all parent classes
  • . _module_class defines the module in which it resides
  • Class corresponding to. _class_instance
  • Dictionary attributes of. _dict_class

Interaction between two objects:

  • Man-dog Round System
class Player:               #Game player
    def __init__(self,name,att,hp):
        self.name=name  #Name
        self.att=att    #Aggressivity
        self.hp=hp      #Blood volume

    def att_dog(self,dog):  #Attacks on dogs
        dog.hp-=self.att


class Dog:
    def __init__(self, att, hp):
        self.att = att  #Aggressivity
        self.hp = hp    #Blood volume

    def att_Player(self, player):   #Attacks on people
        player.hp -= self.att

p1=Player('pro',10,100)
monster=Dog(10,50)
p1.att_dog(monster)
print(p1.hp,p1.att)
print(monster.hp)

Class Namespaces and Objects, Instance Spaces

Creating a class creates a class namespace that stores all the variable names we define. These names are attributes.

There are two attributes of a class:

  • Static attributes
    • Variables defined directly in classes
  • Static attributes
    • Methods defined in classes

Three Characteristics of Functions

  • inherit
  • polymorphic
  • encapsulation

inherit

In object-oriented programming, when we define a new class, we can inherit from an existing class, which is called a Subclass.

The inherited classes are called base, father and super.

single inheritance

class Animal:
    def run(self):
        print("Animal is running")

class Dog(Animal):
    # def run(self):
    #     print("Dog is running")
    pass
class Cat(Animal):
    # def run(self):
    #     print("Cat is running")
    pass

dog=Dog()
cat=Cat()
dog.run()
cat.run()

#Animal is running
#Animal is running

If there is a method of the same name in the parent class in the subclass, the method of the source parent class is overridden.

class Animal:
    def run(self):
        print("Animal is running")

class Dog(Animal):
    def run(self):
        print("Dog is running")

class Cat(Animal):
    def run(self):
        print("Cat is running")

dog=Dog()
cat=Cat()
dog.run()
cat.run()

#Dog is running
#cat is running

multiple inheritance

  • The so-called multiple inheritance means that python's class can have more than two parent classes, that is, class A, class B, class C, and class A and class B are inherited at the same time. In this case, the attributes and methods in A and B can be used in C.
  • In fact, after Python 2.2, the search order of base classes in multi-inheritance is a breadth-first algorithm.
class A:
    def foo(self):
        print("A foo")
class B:
    def foo(self):
        print("B foo")
    def bar(self):
        print("B bar")

class C1(A,B):
    pass

class C2(A,B):
    def bar(self):
        print("C2 bar")
class D(C1,C2):
    pass

test=D()
test.bar()
test.foo()


#C2 bar
#A foo

polymorphic

Polymorphism refers to the fact that a class of things has many forms. (An abstract class has many subclasses, so the concept of polymorphism depends on inheritance.)

  • Sequence types come in many forms: strings, lists, tuples
  • There are many forms of animals: humans, dogs and pigs.
import abc
class Animal(metaclass=abc.ABCMeta): #The same kind of thing: animals
    @abc.abstractmethod
    def talk(self):
        pass
 
class People(Animal): #One of the animal forms: human beings
    def talk(self):
        print('say hello')
 
class Dog(Animal): #Animal Form II: Dogs
    def talk(self):
        print('say wangwang')
 
class Pig(Animal): #Animal morphology three: Pigs
    def talk(self):
        print('say aoao')

Private Attributes

Within a class, there can be attributes and methods, while external code can manipulate data by calling instance variables directly.

class Dog:
    def __init__(self, att, hp):
        self.att = att
        self.hp = hp

    def att_Player(self, player):
        player.hp -= self.att
monster=Dog(10,50)
monster.hp=40
print(monster.hp)

#40

As can be seen from the above, the external can freely modify the attributes of an instance. If you do not want to be accessed externally, you can add two underscores before the attribute name (in python, if the variables of an instance begin with double underscores, they become a private variable, which can only be accessed internally, but not externally).

Access after writing private attributes requires that the corresponding access method be written in the class.

class Dog:
    def __init__(self, att, hp):
        self.att = att
        self.__hp = hp

    def att_Player(self, player):
        player.hp -= self.att
    def get_hp(self):
        print(self.__hp)
monster=Dog(10,50)
monster.get_hp()

#50

encapsulation

Hide the attributes and implementation details of the object, and only provide public access to the outside world.

Advantages of doing so:

  • Change can be isolated
  • Easy to use
  • Improving security
  • Improving reusability

Principles of encapsulation:

  • Hide content that does not need to be provided to the outside world
  • Hide attributes and provide public access to them.

Posted by seanrock on Tue, 06 Aug 2019 04:43:22 -0700