Basic Python Tutorial "reading notes"-2016/7/4

Source: Internet
Author: User

Hope to continue to update through the blog park, share and record the basic knowledge of Python to the advanced application of the dots drop!

Second Wave: The 7th chapter is more abstract

[Overview] creating your own objects is the core concept of Python! Python is called an object-oriented language. Describes how to create objects, as well as the concepts of polymorphism, encapsulation, methods, attributes, superclass, and inheritance.

[7.1] The magic of the object

The term object in object-oriented programming is basically a collection of data (attributes) and a series of methods that can access and manipulate the data. The most important benefits of an object include the following:

   polymorphic polymorphism: means that you can use the same action for objects of different classes.

  Encapsulation Encapsulation: Working details of hidden objects in the external world.

  Inherit Inheritance: A Class object that is based on a general class-specific resume.

The most interesting feature of object-oriented programming is polymorphism.

[7.1.1] Polymorphism

Polymorphism means that even if you don't know what type of object the variable refers to, you can manipulate it, and it behaves differently depending on the type of object (or Class).

1. Polymorphism and methods

Functions that are bound to object attributes are called method methods.

2. Multiple forms of polymorphism

Polymorphism is used when you do not know what the object is, but also "do something" with the object. Many of the built-in operators and functions have polymorphic properties. The only thing that can ruin polymorphism is to use the function display to check the type, such as type, isinstance, and Issubclass function.

[7.1.2] Package

Encapsulation is the principle of hiding excess information from other areas in the global scope. As with polymorphism, they help to process program components without worrying too much about extra detail.

Encapsulation is not equivalent to polymorphism. Polymorphism can have a method call for an object that does not know what class (or object type) it is, and encapsulation can be used directly without worrying about how the object is constructed.

[7.1.3] Inheritance

For example, if you have a class and want to create a very similar class, the new class Ken will just add a few methods. When you write a new class, you do not want to copy all of the old class's code, and then you use the inheritance of the class.

[7.2] Classes and types

What is a class and what is different or the same as its type.

What is the [7.2.1] class?

A class is an object. All objects belong to a class, which is called an instance of class instance. For example, birds are examples of "birds". This is a generic class with a lot of subclasses. "Birds" can be imagined as a collection of all birds, and "Lark Birds" is a subset of them. When an object belongs to a class when another object belongs to a subset of the class, the former is called the latter subclass subclass, so "Lark Bird" is a subclass of "birds". On the contrary, "birds" is a super-class superclass of "Lark Birds".

In Python, it is customary to use the singular noun and capitalize the first letter.

Defining subclasses is just the process of defining more methods.

[7.2.2] Create your own class

__metaclass__=type

Class Person:

def setName (self,name):

Self.name=name

def getName (self):

Return Self.name

def greet (self):

Print "hello,world! I ' m%s. "% Self.name

In the syntax of the new class, you need to place the assignment statement __metaclass__=type where the module or script begins.

This example contains 3 method definitions, except that they are written in the class statement, and everything is like a function definition. Person is the name of the class. The class statement creates a subset of namespaces where the function is defined. The self parameter looks a little strange, and it is a reference to the object itself. When calling Foo's setname and greet functions, Foo automatically passes itself as the first argument to the function, so it is visually named self. Because it is always the object itself, it is customary to always call self.

The attribute is accessible externally.

Foo.name

If you know that Foo is an instance of person, then hey can see Foo.greet () as a handy shorthand for Person.greet (foo).

[7.2.3] features, functions, and methods

The self parameter is actually the difference between a method and a function. Method binds their first parameter to the owning instance. Therefore this parameter can not be provided.

"ToDo: Another discussion on privatization"

Python does not directly support private methods, but relies on the programmer to grasp the timing of Izai external features modification. After all, you should know how to use the object before you use it, but you can use some tips to achieve the effect of private features.

To make a method or attribute private (inaccessible from outside), simply precede its name with a double underscore :

Class secretive:

def __inaccessible (self):

Print "Bet You can ' t see me ..."

def accessible (self):

Print "The Secret message is:"

Self.__inacessible ()

__inacessible is now inaccessible from outside, and access can be used inside the class. In the internal definition of a class, all names that begin with a double underscore are "translated" into the form preceded by a single underline and thunder.

If you do not need to use this method, but want to let other objects do not access internal data, you can use but underline. Names preceded by underscores are not imported with the import statement with the model (from module import *).

namespaces for [7.2.4] Classes

All code in the class statement executes the---class namespace in a special namespace class namespace. This namespace can be accessed by all members within the class. The definition of a class is actually a block of code execution.

[7.2.5] Specify super-tired

Subclasses can extend the definition of a superclass. You can specify a superclass by writing other thunders in parentheses after the class statement.

Class Filter:

def init (self):

Self.blocked=[]

def filter (self,sequence):

return [x for x in sequence if x not in self.blocked]

Class Spamfilter (Filter): #SPAMFilter是Filter的子类

def init (self): #重写Filter超类中的init方法

self.blocked=[' SPAM ']

Note the two key points of the Spamfilter definition:

This overrides the init definition of the filter in a way that provides a new definition.

The filter method is defined as inherited from the filter class, so it is not necessary to rewrite its definition.

The second point reveals the usefulness of inheritance.

[7.2.6] Investigation of inheritance

If you want to see if a class is a subclass of another class, you can use the built-in Issubclass function:

Issubclass (Spamfilter,filter)

If you want to know the base class of a known class, you can directly use its special characteristics __bases__:

Spamfilter.__bases__

Similarly, you can use the Isinstance method to check whether an object is an instance of a class:

Isinstance (S,spamfilter)

[7.2.7] Multiple Super tired

__bases__ This plural form implies that it may have more than one base class.

Subclasses inherit all the behavior from their own superclass. Called Multiple inheritance (multiple inheritance), is a very useful tool.

When using multiple inheritance, there is a need to be aware of. If a method inherits from more than one superclass, you must pay attention to the order of the superclass: The method in the class that inherits first overrides the method in the inherited class. If the superclass shares a superclass, the order in which the superclass is accessed when a given method or attribute is found is called the MRO (method Resolution order, methods decision sequence).

[7.2.8] Interface and introspection

The concept of "interface" is related to polymorphism. When dealing with polymorphic objects, only the interfaces (or "protocols") that are concerned about it can---the methods and features that are exposed. In Python, you do not have to show which methods an object must contain in order to receive it as a parameter.

You can check to see if the required method already exists:

HASATTR (TC, ' Talk ')

In the above code, the object TC has a feature called talk, but there is no fnord feature. If necessary, you can even check whether the talk feature is callable:

Callable (GetAttr (TC, ' Talk ', None))

[7.3] Some thoughts on object-oriented design

Give some points:

Put the objects that belong to a class together. If a function manipulates a global variable, it is best for both to appear as attributes and methods inside the class.
Don't let the object get too close. Methods should only care about the characteristics of their own instances.

Be careful with inheritance, especially multiple inheritance.

Simple, most methods should be able to be read in 30 seconds, the code line control in one page or a screen.

  The following methods should be tried when considering what classes are needed and what methods are required for the class:

(1) write down a description of the problem (what does the program do?) ), underline all nouns, verbs, and adjectives.

(2) for all nouns, as a possible class.

(3) For all verbs, as a possible method.

(4) For all adjectives, as a possible characteristic.

(5) Assign all methods and attributes to the class.

This is the object-oriented type of sketch. You can also consider the relationships between classes and objects and their role, and you can refine the model with the following steps:

(1) write down a series of use cases, that is, the application of the scene, try to include all the functions.

(2) Consider each use case to ensure that the model includes everything needed.

"7.4" summary

objects: objects include attributes and methods. An attribute is simply a variable that is part of an object, and a method is a function stored inside an object. The difference between a method and other functions is that the method always takes the object as its first parameter, which is generally called self.

class: A class represents a collection of objects, and each object has a class. The primary task of a class is to define the method that it uses for its instances.

Polymorphism : polymorphism is an attribute that implements the same treatment of objects of different types and classes. You do not need to know which class the object belongs to to invoke the method.

Encapsulation: objects can hide their internal state.

Inheritance: A class can make a subclass of one or more classes. Subclasses inherit all methods from the superclass.

interface and introspection: you need to know exactly what methods and features the object has, and some functions can help with this work.

Object-oriented design: It is important to create easy-to-understand designs.

Basic Python Tutorial "reading notes"-2016/7/4

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.