Creating a Self object 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 + 2
- 3
- >>> ' fish ' + ' license '
- ' Fishlicense '
Copy Code
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
- >>> Add (' Hello. ', ' world ')
- ' Hello.world '
Copy Code
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
Copy Code
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 '
Copy Code
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
Copy Code
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
Copy Code
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
Copy Code
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 have a self! '
- >>> def function ():
- print "I don ' t"
- >>> instance = Class ()
- >>> Instance.method ()
- I have a self!
- >>> Instance.method = function
- >>> Instance.method ()
- I don ' t
Copy Code
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!
Copy Code
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 if x not in self.blocked]
- Class Spamfilter (Filter): #SPAMFilter是Filter的子类
- def init (self): #重写Filter类中的init方法
- self.blocked = [' SPAM ']
Copy Code
Filter is a generic class for filtering sequences, in fact it cannot filter anything:
- >>> f = Filter ()
- >>> F.init ()
- >>> F.filter ([+])
- [1, 2, 3]
Copy Code
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 ']
Copy Code
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
Object-oriented features of Python (inheritance, encapsulation, polymorphism)