Basic Python Tutorials (eight)

Source: Internet
Author: User

Tags: principle universal Start int method is simple parameter binding parameter

Creating your Own objects (classes) is a very central concept of python, in fact, Python is called an object-oriented language, and this chapter describes how to create objects. and object-oriented concepts: inheritance, encapsulation, polymorphism.

    • Polymorphic: You can use the same action for objects of different classes.
    • Encapsulation: The work details of hidden objects in the external world.
    • Inheritance: A specialized class object is built on the basis of a common class.

Polymorphic

The most interesting feature of object-oriented programming is that it is a feature that makes most of the person faint. So, let's start by introducing this.

Polymorphism means "There are many forms". Polymorphism means that even if you do not know what the object class is referenced by a variable, you can manipulate it, and it behaves differently depending on the type of object (or Class).

From the simplest of beginnings

Polymorphism is used when you do not know what the object is, but also "do something" with the object. This is not limited to methods----Many of the built-in operators and functions have polymorphic properties, consider the following example:

>>> 1 + 23>>> ' fish ' + ' license ' fishlicense '

The addition operator here can work for numbers (integers in this case) and for strings (and other types of sequences). Suppose you have a function called Add, which adds two objects. Then you can directly define it as the form above, for many types of parameters can be used, as follows:

>>> def add (x, y):    return x+y>>> Add 3>>> Add (' Hello. ', ' world ') ' Hello.world '

It looks a little silly, but the key is that the parameter can be any object that supports addition.

If you need to write a function that prints the length of the object, only the object has a length (the Len function is available).

>>> def length_message (x):    print "The length of", repr (x), "is", Len (x)    >>> length_message (' Chongshi ') The length of  ' Chongshi ' is 8>>> length_message ([]) the length of  [1, 2, 3] is 3

The Len function is used to calculate the length, repr is used to place the contents of the function, and the REPR function is one of the polymorphic properties---can use for anything.

Many functions and operators are polymorphic, and most of the programs you write may be, even if you do not intend to do so.

Packaging

Encapsulation is the principle of hiding excess information from other areas in the global scope.

Encapsulation sounds a bit polymorphic, because they are abstract principles---they all help deal with program components without worrying too much about the extra details, just like the function does.

But encapsulation is not the same as polymorphism. Polymorphism allows the user to make method calls to objects that do not know what class (or object type) it is, and encapsulation can be used directly without caring about how the object is constructed.

After you create an object (called a class by calling a function like that), bind the variable C to the object. You can use the SetName and GetName methods (assuming there are already)

>>> C = closedobject () >>> c.setname (' Sir Lancelot ') >>> C.getname () ' Sir Lancelot '

Inherited

We don't want to write the same piece of code several times, and the previously used function avoids this. But now there is a more delicate question. If you already have a class and want to create a very similar class, just add a few methods.

For example, we want to build birds, fish and mammals on the basis of animal species.

The above features will be deeply understood in the light of subsequent learning.

================================

To create your own class

Finally, you can create your own class, and first look at a simple 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

Note: In the syntax of the new class, you need to place the assignment statement _metaclass_ = type at the beginning of the module or script.

A class of person is created, which contains three method definitions, but the self looks a little strange, it is a reference to the object itself.

Let's create an example to see:

>>> Huhu = person () >>> huhu.setname (' Hu Zhiheng ') >>> huhu.greet () Hello, world! I ' m Hu Zhiheng

Should be able to illustrate the usefulness of self, when calling Huhu's SetName and greet functions, Huhu automatically passes itself as the first parameter into the function----so it is vividly named the Everyone may have their own name, but because it is always the object itself, it is customary to always call self.

As before, features can also be accessed externally:

>>> huhu.name ' hu Zhiheng ' >>> huhu.name = ' Yoda ' >>> huhu.greet () Hello, world! I ' M Yoda

attributes, 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, so this parameter does not have to be provided. So you can bind an attribute to a normal function so that there is no special self argument:

>>> Class class:    Def method (self):        print ' I has a self! '        >>> def function ():    print "I don ' t"    >>> instance = Class () >>> Instance.method () I Has a self!>>> Instance.method = function>>> instance.method () I don ' t

The self parameter does not depend on how the method is called, the instance invocation method is currently used, and other variables that reference the same method can be used arbitrarily:

>>> class Bird:    song =  ' squaawk! '    def sing (self):        print self.song        >>> bird = Bird () >>> bird.sing () squaawk!>>> Birdsong = bird.sing>>> Birdsong () squaawk!

To specify a super class

Subclasses can extend the definition of a superclass. You can specify a superclass by writing other class names inside the parentheses after the class statement:

Class Filter:    def init (self):        self.blocked = []    def Filter (self, Sequence):        return [x for x in sequence I f x not in Self.blocked]class spamfilter (Filter):  #SPAMFilter是Filter的子类    def init (self):        # Overriding the Init method in the filter class        self.blocked = [' SPAM ']

Filter is a generic class for filtering sequences, in fact it cannot filter anything:

>>> f = Filter () >>> f.init () >>> f.filter ([i]) [1, 2, 3]

The user of the filter class is that it can be used as the base class for other classes (superclass, called "Parent class in Java"), such as the Spamfilter class, which can filter "SPAM" in the sequence.

>>> s = spamfilter () >>> s.init () >>> s.filter ([' SPAM ', ' spamd ', ' SPAM ', ' HELLO ', ' World ', ' SPAM ']) [' Spamd ', ' HELLO ', ' World ']

Survey inheritance

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

>>> Issubclass (Spamfilter, Filter) true>>> issubclass (filter,spamfilter) False

Basic Python Tutorials (eight)

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.

Tags Index: