Introduction to Python

Are you dating anyone? ! [] (img – blog. Csdnimg. Cn / 20200911223… _ =120×120)

No, just a new one

Today we are going to use Python New for an object

Process oriented VS Object oriented

1) Process oriented

The core is process (pipeline thinking). Process is the steps to solve a problem. Designing for process is like carefully designing an assembly line, thinking about what to do and when.

Advantages: ** greatly reduces the complexity of writing programs by simply stacking the code along the steps to be performed.

Disadvantages: ** an assembly line or process is designed to solve a problem, and the code depends on the whole.

** Application scenarios: ** Well-known examples include the Linux kernel, Git, and Apache HTTP Server.

2) Object oriented

The core is the object (Godlike thinking), == to understand what the object is, you have to think of yourself as God == In God’s eyes everything that exists in the world is an object, and can be created if it does not exist.

Journey to the west, the object-oriented program design is like Buddha Buddha is to solve the problem of the scriptures to the east datang soil, such as come to mean to solve the problem requires four: tang’s monk, pig eight quit, sand monk, the Monkey King, everyone have their own characteristics and skills (this is the concept of object, characteristics and skills respectively corresponding to the object’s properties and methods)

However, this is not fun, so such as to arrange a group of demons and ghosts, in order to prevent the master and his disciples four people on the way to get killed, and arranged a group of fairies escort, these are the object. Then the sutras began, master and apprentice four and demons, ghosts and immortals tangled with each other until finally obtained the scriptures. The Tathagata doesn’t care what process the master and apprentice follow to get it.

** Advantages: to solve the program’s scalability. ** Changes to a single object are immediately reflected in the entire system, such as changes to the characteristics and skills of a character parameter in the game.

** Disadvantages: poor controllability, ** can not accurately predict the process and results of the process oriented programming assembly line. Once the object oriented program starts, the problem is solved by the interaction between objects, even God can not predict the final result. Therefore, we often see that the modification of a certain parameter of a player is likely to lead to the appearance of Yin Bully’s skill, killing 3 people with a knife, and the game is out of balance.

** Application scenarios: ** Software requirements often change, the change of general requirements are concentrated in the user layer, Internet applications, enterprise internal software, games, etc., are a good place for object-oriented program design to show its skills.

Related noun concepts

1. A group of things (a person, a dog, a tiger, a robot) having the same characteristics.

Object/instance: a specific thing (next door ah Hua, downstairs rich)

Instantiation: the process of class — > objects

== begin to seriously write tutorial ==

Classes and objects are two main aspects of object-oriented programming. A Class can create a new Type, where an Object is an Instance of the Class. The analogy is that you can have variables of type int, that is, variables that store integers are instances (objects) of class int.

Objects can store data using ordinary variables belonging to them. Such variables that are subordinate to an object or class are called fields. An object can also use functions that belong to a class, called methods of the class. These two terms are important because they help us distinguish between functions and variables, which are independent and which belong to classes or objects. In general, fields and methods are called attributes of a class

Fields have two types — they belong to instances or objects of a class, or to the class itself. They are called Instance Variables separately) and class variables (The Class Variables `).

You can create a class using the class keyword. The fields and methods of this class can be listed in indented code blocks.

self

There is only one specific difference between a class method and a normal function — the former must have an extra argument at the beginning of the argument list, and the name must be added to the beginning of the argument list, but you don’t have to assign a value to the argument when you call the function, Python provides it. This particular variable refers to the object itself, which by convention is given the name self.

While you can give this parameter any name you want, it’s highly recommended that you use self — anything else would be frowned upon. Using a standard name has many benefits — any reader of your application will instantly recognize it, and even specialized ides can help you if you use the name self.

Tips for C++/Java/C# programmers self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#.

You must be wondering how Python assigns a value to self and why you don’t have to give it a value. An example may answer these questions. Suppose you have a MyClass class with an instance of MyObject. When you call a method of this object, such as myObject.method (arg1, arg2), Python will automatically convert it to myClass.method (myObject, arg1, arg2) — that’s all that’s special about self.

This also means that if you have a method with no arguments, you must still have one argument — self.

class

The simplest Class (Class) can be shown in the following example (saved as oop_simplestclass.py) :

class Person
    : pass # An empty code block

p = Person() 
print(p)
Copy the code

Output:

python oop_simplestclass.py 
<__main__.Person instance at 0x10171f518> How does it workCopy the code

We create a new class by using the class statement with the name of the class. After it is an indented block representing the body of the class. In this case, we create an empty block of code, identified by the pass statement.

We then create an object for the class by taking its name followed by a pair of parentheses. To verify that our operation was successful, we confirm the type of the variable by printing them out directly. The result tells us that we have an instance in the __main__ module of the Person class.

Note that in this case it also prints out the address of the object in the computer memory where you are stored. The address given in the case will be different from what you would see on your computer, because Python will store objects in any space it finds.

methods

We have already discussed that classes and objects can have methods as well as functions, the only difference being that we have an additional self variable. Now let’s look at the following example (save as oop_method.py).


class Person: 
    def say_hi(self) : 
        print('Hello, everyone? ') 

p = Person() 
p.say_hi() 
# The first two lines can also be written
# Person().say_hi()
Copy the code

Output:

Python oop_method.py How does it workCopy the code

So here we can see how Self is acting. Note that the say_hi method takes no arguments, but traditionally has the self variable in the function definition.

__init__ method

There are a number of method names that have special meaning in Python classes. Now we need to understand the meaning of the __init__ method.

The __init__ method is run immediately when an object of the class is instantiated. This method initializes any target object that you want to operate on. == here you have to note the double underscore == before and after init.

Example (save as oop_init.py) :

class Person: 
    def __init__(self, name) : 
        self.name = name 
    def say_hi(self) :
        print('Hello, my name is', self.name) 
        
p = Person('mywood') 
p.say_hi() 
# The first two lines can also be written
# Person('Swaroop').say_hi()
Copy the code

Output:

Python oop_init.py Hello, my name is Mumu how does it workCopy the code

In this case, we define an __init__ method that takes the name argument (and, of course, the self argument). In this, we create a field, also called name. Notice that although they are both named “name”, these are two different variables. That said, this doesn’t cause any problems **, because the dot in self.name means that the thing called “name” is part of an object called “self”, ** and the other name is a local variable. Since we have made it clear as above which name we are referring to, it does not cause confusion.

When we create a new instance p under the Person class, we do so by writing down the name of the class followed by arguments in parentheses, such as p = Person(‘ mummu ‘).

We do not explicitly call the __init__ method. That’s what makes this approach special.

Now we can use the self.name field in our method, as described in the say_hi method.

Class and object variables

Now that we’ve talked about the functional parts (methods) of classes and objects, let’s look at their data parts. Data parts — that is, fields — are simply ordinary variables bound to the namespace of classes and objects. This means that these names are only valid in the context in which these classes and objects exist. That’s why they’re called namespaces.

** Fields ** have two types — class variables and object variables, which are classified according to whether a class or an object owns these variables.

Class variables ** are Shared — they can be accessed by all instances of the Class. There is only one copy of a class variable, and when any object makes a change to a class variable, the change is reflected in all other instances

Object variables are owned by each independent Object or instance of a class. In this case, each object has a copy of its own fields, that is, they are not shared or associated in any way with fields of the same name in its different instances. Here’s an example to help you understand (save it as oop_objvar.py) :

# coding=UTF-8 
class Robot: 
    """ represents a robot with a name." ""
    # a class variable that counts the number of robots
    population = 0
    def __init__(self, name) : 
        """ Initialize data """ 
        self.name = name 
        print("Initialize {})".format(self.name)) 

        # When someone is created, a robot
        # will increase the population
        Robot.population += 1
    def die(self) : 
        """ I'm hanging up." "" 
        print("{} was destroyed!".format(self.name)) 
        
        Robot.population -= 1 
        
        if Robot.population == 0: 
            print("{} is the last robot".format(self.name)) 
        else:
            print("And {:d} robots at work.".format( Robot.population))
            
    def say_hi(self) : 
        """ Sincere greetings from a robot No problem, you can do it." "" 
        print("Hello, my master called me {}.".format(self.name))
    
    @classmethod 
    def how_many(cls) : 
        """ Print out the current number of robots, population """ 
        print("Now there are {:d} robots.".format(cls.population))

droid1 = Robot("R2-D2") 
droid1.say_hi() 
Robot.how_many()

droid2 = Robot("C-3PO") 
droid2.say_hi() 
Robot.how_many()

print("\n robot is working hard.\n")

print("The robot has done its job and we need to destroy it.") 
droid1.die() 
droid2.die()

Robot.how_many()
Copy the code

The output

Python oop_objvar.py (initialize R2-d2) (Initializes C-3PO) Hello, my master calls me C-3PO. There are two robots at work. The robot is working hard. The robot has done its job and we're going to destroy it. R2-d2 has been destroyed! And one robot at work. C-3po has been destroyed! C-3po is the last robot and there are still 0 robots working.Copy the code

How does it work

This is a long case, but it helps to show the nature of class and object variables. In this case, population belongs to the Robot class, so it is a class variable. The name variable belongs to an object (assigned by using self), so it is an object variable.

Therefore, we refer to the population class variable via Robot. Population instead of self. Population. We call the name object variable with the self.name notation, which is the method in this object. Keep in mind this simple distinction between class variables and object variables. Also note that when an object variable has the same name as a class variable, the class variable will be hidden.

In addition to Robot. Popluation, we can also use self.__class__. Population, since each object references its class via the self.__class__ attribute.

How_many is actually a method that belongs to a class, not an object. This means that we can define it as either a classMethod or a staticMethod, depending on whether we need to know which class the method belongs to. Since we already refer to a class variable, we use classMethod.

We use a Decorator to set thehow_manyMethods are marked as class methods.

You can think of decorators as shortcuts to call a wrapper function, so enable

The @classMethod decorator is equivalent to calling:

how_many = classmethod(how_many)

You’ll notice that the __init__ method uses a name to initialize the Robot instance. In this method, we increase the population by 1 because we add one more robot. You’ll also notice that the self.name value is assigned to each object, which reflects the nature of object variables.

You need to remember that you can only use self to refer to variables and methods of the same object. This is called a property reference.

In this program, we’ll also see how DocStrings are used for classes and methods. We can access the docstrings of our classes at run time via robot.__doc__, or for the docstrings of our methods using robot.say_hi.__doc__.

In the DIE method, we simply decrease the count of robot.population by 1.

All class members are public. There is one exception: If you use a data member and prefix its name with a double underscore, forming a form such as __privatevar, Python uses name adjustment to make it effectively a private variable.

Therefore, you need to follow the convention that any variable name used in a class or object should start with an underscore, and all other names that are not in this format will be public and can be used by any other class or object. Remember that this is only a convention, and Python does not enforce it (except for the double underscore prefix) ==.

All class members (including data members) are public, and all methods in Python are Virtual.

inheritance

One of the great things about object-oriented programming is the reuse of code, and one way to do that is through inheritance. Inheritance is best thought of as implementing types and subtypes between classes

Inheritance is a way to create a new class. In Python, a new class can inherit from one or more of its parents, which can also be called a base class or a superclass. New classes are called derived or subclasses

Now suppose you want to write a program to track faculty and students at a university. There are certain characteristics they all share, such as name, age and address. Other characteristics are unique to them, such as teachers’ salaries, courses and vacations, and students’ grades and tuition.

You can create two separate classes for each type and process them. But adding a common trait means adding it to two separate classes. This quickly makes the program cumbersome.

A better approach would be to create a public class called SchoolMember and have teachers and students inherit from this class, which means that they will be subtypes of this class, and we can add some characteristics unique to that class to those subtypes.

It is also important to note that we reuse the code of the parent class, but we do not need to repeat it in other classes, which is necessary when we use separate types.

In the case envisaged above, the SchoolMember Class would be called either Base Class or Superclass. Teacher and Student classes are called derived or subclasses.

We’ll use the following program as an example (saved as oop_subclass.py) :

# coding=UTF-8 
class SchoolMember: 
    "Stands for any member of the school. ' ' ' 
    def __init__(self, name, age) : 
        self.name = name 
        self.age = age 
        print('(Initializing school members: {})'.format(self.name)) 
        
    def tell(self) : 
        "" Tell me the details about myself. ' ' ' 
        print('Name :"{}" Age :"{}"'.format(self.name, self.age), end="") 
      
        
class Teacher(SchoolMember) : 
     "Is for a teacher. ' ' ' 
    def __init__(self, name, age, salary) : 
        SchoolMember.__init__(self, name, age) 
        self.salary = salary print('(Initializing teacher: {})'.format(self.name)) 
        
    def tell(self) : 
        SchoolMember.tell(self) 
        print(Salary: "{:d}".format(self.salary)) 
        
        
class Student(SchoolMember) : 
    "Is for a student. ' ' '
    def __init__(self, name, age, marks) : 
        SchoolMember.__init__(self, name, age) 
        self.marks = marks
        print('(Initializing student: {})'.format(self.name)) 
                
    def tell(self) : 
        SchoolMember.tell(self) 
        print("{:d}".format(self.marks)) 
        
t = Teacher('Miss Zeng'.30.30000) 
s = Student('Ming'.20.75) 

Print a blank line
print() 

members = [t, s] 
for member in members: 
    # Work for all teachers and students
    member.tell()
Copy the code

Output:

Python oop_subclass.py (initializing school member: Mr. Zeng) (initializing school member: Mr. Zeng) (Initializing student: Mr. Ming) name :" Mr. Zeng "Age :"30" Salary: Name: Xiao Ming Age: 20 Grade: 75Copy the code

How does it work

To use inheritance, we need to define a class followed by a tuple containing the name of the base class.

We then note that the base class’s \ __init__ method is explicitly called through the self variable, so we can initialize the base class part of the object.

It’s important to keep in mind that because we define __init__ methods in the Teacher and Student subclasses, Python doesn’t automatically call the constructor of the base class SchoolMember; you have to explicitly call it yourself.

Conversely, if we do not define an __init__ method in a subclass, Python will automatically call the base class constructor.

We will observe that we can call a method of a base class by prefixing the method name with the base class name and passing in self and the remaining variables.

Note here that when we use the tell method of the SchoolMember class, we can treat an instance of Teacher or Student as an instance of SchoolMember.

Also, you’ll notice that the tell method of the subtype is called instead of the tell method of SchoolMember. One way to understand this is that Python always starts looking for methods in the current actual type, as it did in this case. If it can’t find the corresponding method, it looks for the methods that belong to the base class, one by one, in the order that the class belongs to, as specified by the tuple that follows the subclass when defining it.

A note on terminology — if there is more than one class in the inherited tuple, the situation is called multiple inheritance

.

The end argument is used in the print function of the superclass’s tell() method to print a line and allow the next print to continue on the same line. This is a trick that lets print not print the \ N symbol at the end of the print.

Common term for object orientation

Abstraction/implementation

Abstraction refers to modeling the essential performance, behavior, and characteristics of real-world problems and entities, creating a related subset that can be used to draw program structures to achieve this model. The abstraction includes not only the data properties of such a model, but also defines the interfaces to that data.

The realization of an abstraction is the realization of that data and the interface associated with it. The process of realisation should be transparent and irrelevant to the client.

Encapsulation/interface

Encapsulation describes the concept of hiding data/information by providing interfaces and access functions to data attributes. Direct access to data through any client, regardless of the interface, runs counter to encapsulation unless the programmer allows it. As part of the implementation, the client does not need to know how the data attributes are organized after encapsulation. In Python, all class attributes are public, but the names can be “obfuscated” to prevent unauthorized access, but that’s it, and there are no other precautions. This requires an interface to the data at design time to prevent clients from accessing encapsulated data attributes through non-standard operations.

Note: Encapsulation is not the same as “hiding something private that you don’t want others to see and can change later.”

True encapsulation is a thoughtful abstraction that gives “complete and minimal” interfaces and makes internal details transparent to the outside world

(Note: External transparency means that external callers can get whatever functionality they want without being aware of the internal details)

synthetic

Composition extends the description of classes, allowing multiple different classes to be combined into one large class to solve real-world problems. Composition describes an extraordinarily complex system, such as a class composed of other classes, smaller components that may also be other classes, data attributes and behaviors, all of which together have a “one” relationship with each other.

Derivation/inheritance/inheritance structure

Derivation describes the derivation of new features from a subclass. The new class retains all the data and behavior required by the existing class type, but allows modification or other custom operations without modifying the original class definition. Inheritance describes the way in which a subclass attribute is inherited from an ancestor class. The inheritance structure represents multiple “generations” of derivations, which can be described as a “family tree,” successive subclasses, all related to the ancestor class.

Generalization/specialization

Inheritance-based generalization means that all subclasses have the same characteristics as their parent and ancestor classes. Specialization describes the customization of all subclasses, that is, what attributes make it different from its ancestor class.

Polymorphism and polymorphism

Polymorphism refers to many states of the same thing: water, this thing has many different states: ice, water vapor

The concept of polymorphism describes how objects can be manipulated and accessed through their common properties and actions, regardless of their specific classes.

Ice, water vapor, they all inherit from water, and they all have the same name by becoming clouds, but ice. Change clouds (), and water vapor. Clouding () is a completely different process, although the methods are all called the same

Introspection/reflection

Introspection is also called reflection, and this property shows how an object obtains information about itself at runtime. If an object is passed to you, you can find out what it’s capable of, which is a powerful feature. If Python does not support some form of introspection, the dir and type built-in functions will be difficult to work with. And special attributes like __dict__,__name__, and __doc__

Practice address: www.520mg.com/it