Python3 and so on
In object-oriented languages, classes are the most important part. python naturally has the class mechanism. The class mechanism of python is not very different from that of C ++ and java. Most of the important features of classes are used, and they can be polymorphism, abstract, and encapsulated;
Python3 scope:
Before introducing the class, first introduce the python scope rules;
1. namespace:
Is the ing from the name to the object. The current namespace is mainly implemented through the Python dictionary, but usually does not care about the specific implementation method (unless for performance considerations );
The following are examples of namespaces:
Built-in naming (functions such as abs () and built-in exception names), Global naming in the module, and local naming in the function call. In a sense, the property set of an object is also a namespace.
One important thing to know about namespaces is that there is no connection between namespaces, for example, two different modules may define a function named maximize without confusion-you must reference them with the module name prefix. For example, math has a sin function, which can be called through math. sin;
2. Scope:
A Python program can directly access the namespace's body area. Direct access here means that an incorrect reference to the name will try to find it in the namespace.
Example:
Def scope_test (): def do_local (): spam = local spam # local variable def do_nonlocal (): nonlocal spam = nonlocal spam # domain variable, which is valid throughout the function domain. Def do_global (): global spam = global spam # spam = test spam # global variable, which is effective outside the function; do_local () print (After local assignment:, spam) do_nonlocal () print (After nonlocal assignment:, spam) do_global () print (After global assignment:, spam) scope_test () print (In global scope:, spam) # global variable scope # output: After local assignment: test spamAfter nonlocal assignment: nonlocal spamAfter global assignment: nonlocal spamIn global scope: global spam
Class Definition syntax
Class Definition form:
class className(superClass):
.....
The class definition is like the function definition. It takes effect only after execution. The statement is a function definition, but other statements can also be used.
After entering the class definition section, a new namespace will be created as a local scope. Therefore, all assignments become local variables of the new namespace, in particular, the function definition is bound with a new name here.
When the class definition is complete, a class object is created. That is, the class name;
Class Object:
Class objects support two types of operations: attribute application and instantiation.
Attribute Application Usage: Class Name. Attribute. For example, the class definition is as follows:
Class Myclass: A simple class for Attribute introduction num = 123 def fun (self): return 'Hello world'
So I can use Myclass. num and Myclass. fun as valid property references; return an integer and a method object respectively;
Class Definition instantiation: the class instance uses the function Symbol: Class Name ();
Example: x = Myclass ()
The above creates an instance of a new class and assigns this object to the variable x. This operation is not initialized;
Many classes tend to create objects in the initial state. Therefore, the class may defineInit(), As shown below:
def __init__(self): self.data = []
Class definedInit() Method, the class instantiation operation is automatically called for the newly created class instanceInit() Method. In the following example, you can create a new instance as follows:
X = MyClass ()
When it comes to elasticity,InitThe () method can contain parameters. In fact, the number of parameters passes throughInit() Is passed to the class instantiation operation.
Instance Object:
An instance object is an attribute reference used to operate a class. There are two types of references: data and methods.
Data: similar to java members, it is actually a variable. Like local variables, data attributes do not need to be declared and will be generated when they are used for the first time;
For example:
X = Myclass () # The Myclass class is not declared and can be used directly; x. counter = 1
Method: The method belongs to a class function, and the reference of the method is: x. fun ();
You can also assign method references to variables, which is the same as function assignments;
Xf = x. fun () # note that the self parameter is passed to the variable as the first parameter of the object instance and does not need to be shown and called;
Instance attributes and class attributes
1. instance attributes:
You can bind attributes to an instance by using instance variables or self variables:
class Student(object): def __init__(self, name): self.name = name s = Student('peace') s.score =40
Both name and score are instance attributes;
Two types of attributes:
You can define attributes directly in the class. This attribute is a class Attribute and is categorized into all:
class student: name=peace
Name is a class attribute. all instances of the class can access and direct to the same object;
Inheritance:
Without inheritance, there is no class, And the python class is defined as follows:
Class className (superClass ):
.....
# ClassName is the derived class of superclass.
Instance introduction:
class Animal(object): def run(self): print('Animal is running...')class Dog(Animal): passclass Cat(Animal): pass
For dog and cat, Animal is its parent class.
If the property of the request call cannot be found in the subclass, search for the base class. If the base class is derived from another class, this rule will be applied recursively. Now both the Dog and Cat methods can call the run method.
You can also add the following methods:
class Dog(Animal): def see(self): print('see a dog')
Polymorphism (overwrite ):
A derived class can overwrite its base class. Because the method does not have the privilege to call other methods in the same object, when the method of the base class calls the method of the same base class, it may actually call the override party in the derived class.
Method.
class Dog(Animal): def run(self): print('Dog is running...')class Cat(Animal): def run(self): print('Cat is running...')
Benefits of polymorphism:
Def run_twice (animal): animal. run () animal. run () # test polymorphism: >>> run_twice (Animal () Animal is running... animal is running... >>> run_twice (Dog () Dog is running... dog is running...
For a variable, we only need to know that it is of the Animal type. Without knowing its child type exactly, we can safely call the run () method, while the specific called run () method () the method is applied to Animal, Dog, Cat, or Tortoise objects. It is determined by the exact type of the object at runtime. This is the real power of polymorphism: The caller only calls the object, regardless of the details, when we add an Animal subclass, make sure that the run () method is correctly written, regardless of how the original code is called. This is the famous "open and closed" principle:
Open to extension: Animal subclass can be added;
Disable modification: you do not need to modify functions that depend on Animal type such as run_twice.
5. There is no difference between the instantiation of a derived class and a common class;
Python has two functions for inheritance:
• The isinstance () function is used to check the instance type: isinstance (obj, int) is only available in obj. _ class _ is an int or another type inherited from the int • The issubclass () function is used to check the class inheritance: issubclass (bool, int) is True, because bool is a subclass of the int. However, issubclass (unicode, str) is Fals, because unicode is not a subclass of str (they only share a common ancestor class basestring ).
Multiple inheritance:
Python supports multiple inheritance:
Class className (superClass1, superClass1, superClass2 .....):
.....
# ClassName is the derived class of superClass1, superClass1, superClass2.
Private variable:
You only need to add _ to the front of the data or method, for example, _ spam. The unique name encoding of python replaces _ spam with _ classname _ spam.
In this way, the class name. _ spam cannot be called normally. But if it is fully written, it is still possible to replace it with the class name. _ classname _ spam. At this time, python is defective.
class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score))
For external code, it is impossible to access instance variables. _ name and instance variable. _ score from outside
Exception is also a class:
You can define a derived class for the exception and throw it through rasie;
There are two ways to throw:
1. The derived class defined by raise Classname;
2. raise instance; comes from exception-type instances;
The demo is as follows:
class B(Exception): passclass C(B): passclass D(C): passfor cls in [B, C, D]: try: raise cls() except D: print(D) except C: print(C) except B: print(B)
It should be noted that, if the subsentence of an exception is backward (execpt B is at the beginning), it will print B, B, b-the first matching exception is triggered.