Python3 Quick Start (f) - Python3 Object-Oriented

Python3 Quick Start (f) - Python3 Object-Oriented

I. Introduction to Object-Oriented Technology

1, Introduction to Object-Oriented

Object-oriented programming (Object Oriented Programing, OOP) is a programming idea, subject of OOP as a basic unit of the program, an object contains data and operation data. Three characteristics of object-oriented programming is as follows:
A, encapsulation, can hide implementation details to make the code modular.
B, inheritance, by extending the existing class code reuse, avoid rewriting the same code.
C, polymorphism, encapsulation and inheritance are for the purpose of code reuse, and polymorphism in order to achieve reuse of the interface, such that the derived classes inherit and to ensure that when any instance of a class can correctly calling convention properties and good method.
Object-oriented programming through encapsulation, inheritance, polymorphism achieve the reusability of software engineering, flexibility, scalability three goals.

2, object-oriented terminology

Class (Class) is used to describe a collection of objects having the same properties and methods, and defines the attributes of each object in the set of methods common.
Objects are instances of classes, Python data objects comprises two members (the class and instance variables) and methods.
A method is a function defined in the class.
Class variables are common to all instances of the object class. Class variables defined and in vitro function in the class.
Method overrides: If you can not meet the needs of the subclass inherits from a parent class can be overridden (override).
Inheritance is a derived class (derived class) inherits the base class (base class) fields and methods. Inheritance allows a derived class object as a base class object treated.
Instantiate: create an instance of a class, the specific object class.

3, attributes of the object

In python which everything is an object, each object has three properties: id, type type and value. id is the address of the object, the same object as the same as the id certainly, different objects may be the same value.

# -*- coding:utf-8 -*-
x = 10
print(id(x))
print(type(x))  # <class 'int'>
print(x)

y = 10
print(id(y))
print(type(y))  # <class 'int'>
print(y)

print(x is y)  # True

Second, the definition of the class

1, class definition

Class is an abstract data type, the package is a type of data and the real world operation.
Class definition syntax is as follows:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

After the class is instantiated, its properties can be used to create a class, you can access its class by class name attribute.
Person has the following three properties:
nationality: nationality
name: Name
id: ××× number

import uuid

class Person:
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

They are all substantially the same nationality, and allows direct access by the class or instance, to modify them.
Most of the names are different, and allow an instance of the class to directly access and modify freely.
××× number everyone is not the same, and do not allow direct access to freely modify or by class or instance.

2, class instantiation

import Person

bauer = Person.Person("Bauer")
bauer.hello()

3, the visibility of class members

Python default all members are members of the public, but private members is underlined names beginning with two private members, private members are not allowed direct access, accessible only through internal methods, private members are not allowed to be inherited.
Python via class variables, instance variables, class methods, instance method before adding __a prefix, it can be hidden in foreign, becomes a private variable or function class. Due to the built-in Python variable or function uses __the prefix and suffix, therefore, not recommended for private functions or variables add __prefix and suffix, just add __the prefix.
Python as a dynamic language that allows dynamic increase class or instance attributes and private attributes of a class are not the same inside.
Python class maintains a dictionary for a class of data storage, internal Python dictionary renamed the private members _ClassName + __variable_name, so you can access the corresponding private variables access the new name of the private variable outside the class.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

if __name__ == "__main__":
    bauer = Person("Bauer")
    print(bauer.__dict__)
    print(bauer._Person__id)

"""
output:
{'name': 'Bauer', '_Person__id': 'ed496846-94c7-11e9-80c4-5ce0c5e8bcf0'}
ed496846-94c7-11e9-80c4-5ce0c5e8bcf0
"""

Third, the properties of the class

1, class attributes

Defined directly in the class of property is public property / class attribute, all instances of an object class attributes are common to all classes, so by default property values will only keep a lower class, but not for each instance of the class is saved a.
ClassName.VariableName access class attributes may be used, within the example method may also be used self.__class__.VariableNamefor access.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

    def sayHello(self):
        print("Hello,I come from %s" % self.__class__.nationality)

if __name__ == "__main__":
    bauer = Person("Bauer")
    bauer.sayHello()
    jack = Person("Jack")
    print(Person.nationality, bauer.nationality, jack.nationality)
    bauer.nationality = "USA"
    print(Person.nationality, bauer.nationality, jack.nationality)
    Person.nationality = "Germany"
    print(Person.nationality, bauer.nationality, jack.nationality)

"""
output:
Hello,I come from China
China China China
China USA China
Germany USA Germany
"""

Class attributes can also be accessed directly through the class of direct access by example; an instance of a class by class of property if modified, in essence, is to add a class attribute with the same name instance attributes for instance, for real did not affect class attribute, it will not affect other instances of the class attribute values ​​acquired; modified by the class attribute class, is bound to change the value of the class attribute, all instances of the class that are affected.

2, examples of the properties

Examples of property, also known as a member of a property or member variable, each instance of an object class is held by a separate property. Class instance attributes must init declared methods.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

if __name__ == "__main__":
    bauer = Person("Bauer")
    jack = Person("Jack")
    print(bauer.name, jack.name)
    bauer.name = "Jack Bauer"
    jack.name = "Chen Jack"
    print(bauer.name, jack.name)
    #print(Person.name)  ## AttributeError: type object 'Person' has no attribute 'name'

"""
output:
Bauer Jack
Jack Bauer Chen Jack
"""

By accessing class member properties will complain:
Print (person.name)
instance properties can be directly accessed and changed by the object instance is unique for each instance of an object, an instance of an object instance properties are subject to change without affecting other instances the value of the same attribute. Examples of the attribute values can not access and modify classes.
Python as a dynamic language, can increase the dynamic properties of the object outside the class instance.

3, private property

Examples of private property and property must __init__be declared in the method, but the private property of the attribute name needs a double underscore __at the beginning, such as Person of the __idproperty. Private property is a special property of example, only within the object instance (or member method private methods), and disallow the outside by way of example an object instance of the object class or direct access can not be inherited by subclasses.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

if __name__ == "__main__":
    bauer = Person("Bauer")
    bauer.hello()
    # print(bauer.__id) # AttributeError: 'Person' object has no attribute '__id'
    # print(Person.__id) # AttributeError: type object 'Person' has no attribute '__id'

"""
output:
Hello, I am Bauer, I come from China, My ID is c0c02dcc-94aa-11e9-972c-5ce0c5e8bcf0
"""

Private property can not directly access the class, the object can not be accessed directly by way of example, but can be accessed via the private attribute member methods.
Private property can by members of the methods or 实例对象._类名__私有变量名to access manner.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

    def get_id(self):
        return self.__id

if __name__ == "__main__":
    bauer = Person("Bauer")
    bauer.hello()
    print(bauer._Person__id)
    print(bauer.get_id())

"""
output:
Hello, I am Bauer, I come from China, My ID is c0c02dcc-94aa-11e9-972c-5ce0c5e8bcf0
354547ae-94ab-11e9-a52c-5ce0c5e8bcf0
354547ae-94ab-11e9-a52c-5ce0c5e8bcf0
"""

Fourth, the special attributes of the class

Python has some built-in classes, special attributes, its name is double-underlined __at the beginning and double-underlined __at the end. Special property is not private property, you can go directly accessed through instance object outside the class, and all have their own special significance.
__doc__A description for the class.
__module__It represents the operation of the object corresponding to the current definition of a class where the module name.
__class__It represents the class name of the current object corresponding to the operation.
__dict__Is a dictionary, all members of the class member holds all the properties (including the attributes and methods) of the object or instance.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def __hello(self):  # 私有方法
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

    def say_hello(self):  # 成员方法/实例方法
        self.__hello()

    @classmethod
    def get_nationality(cls):  # 类方法
        return cls.nationality

    @staticmethod
    def add(a, b):  # 静态方法
        return a + b

    @property
    def id(self):
        return self.__id

if __name__ == "__main__":
    bauer = Person("Bauer")
    print("Person Object")
    print(bauer.__class__)
    print(bauer.__doc__)
    print(bauer.__dict__)
    print(bauer.__module__)

    print("Person Class")
    print(Person.__class__)
    print(Person.__doc__)
    print(Person.__dict__)
    print(Person.__module__)

"""
output:
Person Object
<class '__main__.Person'>
None
{'name': 'Bauer', '_Person__id': 'f545f99a-94b5-11e9-aa3f-5ce0c5e8bcf0'}
__main__
Person Class
<class 'type'>
None
{'__module__': '__main__', 'nationality': 'China', '__init__': <function Person.__init__ at 0x7f49941d5d90>, '_Person__hello': <function Person.__hello at 0x7f49941d5e18>, 'say_hello': <function Person.say_hello at 0x7f49941d5ea0>, 'get_nationality': <classmethod object at 0x7f499b470be0>, 'add': <staticmethod object at 0x7f499b470c18>, 'id': <property object at 0x7f499b464908>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
__main__
"""

实例对象.__dict__And the 类.__dict__values are different, 实例对象.__dict__the values of the members contains only attributes and private attributes, 类.__dict__the value contained in the class methods, and all class attributes;
__module__and __class__values can be used to instantiate an object reflecting a class.

Fifth, class methods

1, member methods

Members of the object class instance methods to access, the first argument must be the current instance of the object, usually written as self; but the method can also be called by a member of the class name, then you need to manually instance of the object passed to members of a class method the self argument.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

if __name__ == "__main__":
    bauer = Person("Bauer")
    bauer.hello()
    Person.hello(bauer)

"""
output:
Hello, I am Bauer, I come from China, My ID is 0e4d0606-94af-11e9-a958-5ce0c5e8bcf0
Hello, I am Bauer, I come from China, My ID is 0e4d0606-94af-11e9-a958-5ce0c5e8bcf0
"""

2, private methods

The method is based on the private member method begins with a double underline. Private methods can only be accessed inside instance methods, and can not be inherited by subclasses; The first argument must also be a private method of the current instance of the object itself, usually written as self. Typically, the front and rear double underlined naming method for Python's built-in, custom method is not recommended for use. Plus double-underlined if the developers are named members of the previous method, the corresponding member method is public.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def __hello(self):  # 私有方法
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

    def say_hello(self):  # 成员方法/实例方法
        self.__hello()

if __name__ == "__main__":
    bauer = Person("Bauer")
    bauer.say_hello()

"""
output:
Hello, I am Bauer, I come from China, My ID is 0e4d0606-94af-11e9-a958-5ce0c5e8bcf0
"""

3, class methods

 The method is based on class @classmethodmembers ways to decorate the class method requires the first argument must be the current class. The method may be carried out by way of example class object access, also directly by the class name to access, and the first parameter represents the current class is generally written as cls. Class class method only access attribute, not instance attribute, the first parameter is representative of the current class cls, rather than indicative of self instance object.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def __hello(self):  # 私有方法
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

    def say_hello(self):  # 成员方法/实例方法
        self.__hello()

    @classmethod
    def get_nationality(cls):  # 类方法
        return cls.nationality

if __name__ == "__main__":
    bauer = Person("Bauer")
    print(bauer.get_nationality())
    print(Person.get_nationality())

"""
output:
China
China
"""

4, static methods

Static method is based on @staticmethodmember method to decorate the static method is usually accessed through the class name, it can also be accessed through an object instance of the class. In essence, we have no static methods associated with the class, because static methods are not required to transfer the object or class instance parameters.
Internal static methods can access class variables, it can be used as ClassName.Varaible_Nameway to access class variables.
Static method parameter is not required, it is possible to arbitrarily to the static methods to define parameters, if a static method defined parameter representing the current class, then it can access the class attributes; if a static method defined parameter representing object instance of the current class, then you can access the instance attribute; if the current class is not defined parameter or parameters to the current instance of the static method, it can not access any attributes or instance of the object class.

import uuid

class Person(object):
    sum = 0
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())
        Person.sum += 1

    def __hello(self):  # 私有方法
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

    def say_hello(self):  # 成员方法/实例方法
        self.__hello()

    @classmethod
    def get_nationality(cls):  # 类方法
        return cls.nationality

    @staticmethod
    def add(a, b):  # 静态方法
        return a + b

    @staticmethod  #静态方法,内部使用类变量
    def counter():
        return Person.sum

    @staticmethod
    def get_counter(cls):  #静态方法,传递当前类
        return cls.sum

if __name__ == "__main__":
    bauer = Person("Bauer")
    print(bauer.add(1, 2))
    print(Person.add(1, 2))
    print(Person.counter())
    print(Person.get_counter(Person))

"""
output:
3
3
1
1
"""

5, property methods

Attribute method is @propertya member method to decorate, and is a member of the method instance properties of ways to access the instance attributes; attribute method first argument must be the current instance of the object, and the attribute method must have a return value.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def __hello(self):  # 私有方法
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

    def say_hello(self):  # 成员方法/实例方法
        self.__hello()

    @classmethod
    def get_nationality(cls):  # 类方法
        return cls.nationality

    @staticmethod
    def add(a, b):  # 静态方法
        return a + b

    @property
    def id(self):
        return self.__id

if __name__ == "__main__":
    bauer = Person("Bauer")
    print(bauer.id)
    # print(bauer.id()) # TypeError: 'str' object is not callable

"""
output:
631baef4-94b3-11e9-babe-5ce0c5e8bcf0
"""

Python attribute method is commonly used in a series of internal property logic calculation method, the final calculation result is returned.

6, binding method

Methods inside the class definition, in the absence of any decorator modified, in order to process with automatic transmission values of self keyword to target binding, regardless of the write do not write self. By default, the methods within a class are bound to the subject method. Bound methods A bound to the body who will come to pass as the first parameter, bound to the methods of the class to use the object is no sense.
The method of binding to the object, the object will be called when the parameters are automatically passed; bound to the methods of the class, when the class will be invoked automatically passed as a parameter.
The method of binding a non-static method, does not bind the class or object, anyone can call, there is no automatic pass effect value. Non-binding method is not the class or object binding, classes and objects can call, but there is no automatic transfer value.

# -*- coding:utf-8 -*-
import time
import hashlib
import pickle
import os

"""
HOST = "127.1.1.1"
PORT = 3306
DB_PATH = r"/usr/lib/mysql/db"
"""

class MySQL:
    HOST = "127.1.1.1"
    PORT = 3306
    DB_PATH = r"/var/lib/mysql"

    @staticmethod
    def create_id():
        m = hashlib.md5(str(time.perf_counter()).encode("utf-8"))
        return m.hexdigest()

    def __init__(self,host,port):
        self.id = self.create_id()
        self.host = host
        self.port = port

    @classmethod
    def from_conf(cls):
        return cls.HOST, cls.PORT

    def save(self):
        file_path = r"%s%s%s"%(MySQL.DB_PATH,os.sep,self.id)
        #将对象以二进制的形式写到磁盘
        pickle.dump(self,open(file_path,"wb"))

    def get(self):
        file_path = r"%s%s%s" % (MySQL.DB_PATH, os.sep, self.id)
        return pickle.load(open(file_path,"rb"))

if __name__ == '__main__':
    conn1 = MySQL("127.0.0.1","3306")
    print(conn1.id)
    conn1.save()
    result = conn1.get()
    print(result.id)

Special method VI class

Python has some built-in classes, special method name is double underlined __at the beginning and double-underlined __at the end. Special methods are not private methods, you can go directly accessed through instance object outside the class, and all have their own special significance.

. 1, the init constructor

__init__The method is the class constructor method is a special class, called automatically when the class object is created, you can not have a return value. It is defined as follows:

def __init__(self):
    pass

__init__The first argument must be an instance method of creation itself, it is generally recommended to use self. Examples of property class, private property must __init__be declared method.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())
        print(self.name, "__init__")

if __name__ == "__main__":
    bauer = Person("Bauer")

"""
output:
Bauer __init__
"""

2, del destructor

__del__Class destructor method is, when the object is released in the memory, automatically triggers the execution of __del__the method, such as when the exit scope instance object or perform an instance object del operation.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())
        print(self.name, "__init__")

    def __del__(self):
        print(self.name, "__del__")

if __name__ == "__main__":
    bauer = Person("Bauer")
    del bauer

"""
output:
Bauer __init__
Bauer __del__
"""

3、str

If a class is defined in __str__the method, then the default output at the time of print target __str__return value, otherwise print out the memory address of the object instance.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())
        print(self.name, "__init__")

    def __del__(self):
        print(self.name, "__del__")

    def __str__(self):
        return "name: %s, nationality: %s, id: %s" % (self.name, self.nationality, self.__id)

if __name__ == "__main__":
    bauer = Person("Bauer")
    print(bauer)

"""
output:
Bauer __init__
name: Bauer, nationality: China, id: 0a9a80c2-94c0-11e9-891d-5ce0c5e8bcf0
Bauer __del__
"""

4 GetItem , setitem , DeLiTE

__setitem__, __getitem__, __delitem__ For indexing operations, such as the operation of the dictionary, respectively, set, get, delete an entry, data. By __setitem__, __getitem__, __delitem__means for defining classes encapsulate dictionary, so that the dictionary can be controlled key operation, especially a delete operation.
If a class implements __setitem__, __getitem__, __delitem__method, you can perform some operations dictionary.

class ChineseDict(object):
    def __init__(self, init=None):
        self.__dict = init if init is not None else {}

    def __setitem__(self, key, value):
        print('__setitem__', key)
        self.__dict[key] = value

    def __getitem__(self, item):
        print('__getitem__', item)
        return self.__dict.get(item, None)

    def __delitem__(self, key):
        print('__delitem__', key)
        if key is not None and key.startswith('wh'):
            print('You can not delete this item ')
            return None
        return self.__dict.pop(key, None)

if __name__ == "__main__":
    dic = ChineseDict(init={'name': 'Bauer', 'nationality': 'China', "age": 23})
    print(dic["name"], dic["nationality"], dic["age"])
    del dic["age"]
    print(dic["age"])

"""
output:
__getitem__ name
__getitem__ nationality
__getitem__ age
Bauer China 23
__delitem__ age
__getitem__ age
None
"""

5、new

__new__The method will __init__be executed before the method creates and returns a new instance of the object, and then passed to __init__. __new__Not a member method, but a static method.
In Python, all objects are in the new class, in order to type (int, str, float, etc.) and class unity, all classes are objects of type type. There is a property in the class __metaclass__can be specified by the current class to which the class is instantiated. The process of creating an object, the constructor is not a __init__method, but the __new__method, __new__the method returns an object, that object constructor.
Examples of class internal object code segment that implements the process:

class PersonType(type):

    def __init__(cls, what, bases=None, dic=None):
        super(PersonType, cls).__init__(what, bases, dic)

    def __call__(cls, *args, **kwargs):
        obj = cls.__new__(cls)
        cls.__init__(obj, *args, **kwargs)
        return obj

class Dog:
    __metaclass__ = PersonType

    def __init__(self,name,age):
        self.name=name
        self.age=age

    def __new__(cls, *args, **kwargs):
        return object.__new__(cls)

if __name__ == "__main__":
    obj = Dog("Dog", 3)
    print(obj.name, obj.age)

"""
output:
Dog 3
"""

6、call

Class defined __call__method, class object instance as a function to call, and the function is called by the function name ().

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def __call__(self, *args, **kwargs):
        print("name: ", self.name, "args: ", *args)

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

if __name__ == "__main__":
    bauer = Person("Bauer")
    bauer("China", 26)

"""
output:
name:  Bauer args:  China 26
"""

Seven, class inheritance

1, the derived class definition

Python class inheritance in accordance with the method of the parent class has been implemented can be divided into two types:
inheritance: refers to the properties directly inherited from the parent class and method is defined and implemented;
interface inheritance: the only inherit attributes and parent classes method name, method subclass must implement their own specific function codes.
If the number of points according to inherit the parent class, there can be divided into:
single inheritance: inheritance only one parent class.
Multiple inheritance: inherits more than one parent class.

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def walk(self):
        print('%s is walking...' % self.name)

    def talk(self):
        print('%s is talking...' % self.name)

class Teacher(Person):
    def __init__(self, name, age, level, salary):
        super(Teacher, self).__init__(name, age)
        self.level = level
        self.salary = salary

    def teach(self):
        print('%s is teaching...' % self.name)

class Student(Person):
    def __init__(self, name, age, class_):
        Person.__init__(self, name, age)
        self.class_ = class_

    def study(self):
        print('%s is studying...' % self.name)

if __name__ == "__main__":
    t1 = Teacher('Bauer', 33, 'Senior', 20000)
    s1 = Student('Jack', 13, 'A class')

    t1.talk()
    t1.walk()
    t1.teach()

    s1.talk()
    s1.walk()
    s1.study()

"""
output:
Bauer is talking...
Bauer is walking...
Bauer is teaching...
Jack is talking...
Jack is walking...
Jack is studying...
"""

Teacher classes and Student classes inherit Person class, Teacher and Student are Person subclass / derived class, and Person is Teacher and Student parent / base class / superclass;
Teacher and Student inheritance of Person belonging inheritance, and it is a single inheritance;
Teacher class inherits Person's name and age properties, and talk () and walk () method, and expand their level and salary attributes, and teach () method;
Student class inherits Person's name and age property, and Talk () and walk () method, and extend their class attribute, and Study () method;
Teacher and Student on the Person class attributes and methods inherited reflects the reusability of the code, and Teacher and Student extended properties and methods embodied flexible scalability;
subclasses Teacher and Student can redefine the talk parent class in your class definition () and walk () method implementation code change, i.e., a method override override.

2, the derived class constructor

Need to explicitly pass self instance object when the derived class constructor requires explicit call the constructor of the parent class, the attributes of the parent member class is initialized call the constructor of the superclass.
Subclass needs in their __init__constructor called the father of a first row position of the methods, the above code gives two methods:
super(子类名, self).__init__(父类构造参数)such as super.(Teacher, self).__init__(name, age), the recommended way.
父类名.__init__(self, 父类构造参数)Like Person.__init__(self, name, age).

3、isinstance

isinstance may determine whether a certain data type is variable, it may be determined whether the object is a subclass of the class of the object or the object class.
issubclass used to determine whether a class is a subclass of a class returns a bool type data.

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

class Teacher(Person):
    pass

if __name__ == "__main__":
    bauer = Teacher("Bauer")
    print(isinstance(bauer, Person))
    print(issubclass(Teacher, Person))

"""
output:
True
True
""" 

Eight, like multiple inheritance

1, multiple inheritance Profile

Python supports multiple inheritance parent class, subclass inherits all the attributes and methods of the parent class, including all properties and methods of the parent class of the parent class. Although Python supports multiple inheritance, but Python support for multiple inheritance is limited.
When multiple inheritance, use super property will only call a parent class's method first, therefore, to call a specific parent class constructor explicitly call only 父类名.__init__.

If you have the same method name of the parent class, but not in the subclasses of class assigned specific method called explicitly specified, Python will search according to the order of succession from left to right to find the parent class contains methods.

class A(object):
    def __init__(self):
        print("class A")

    def hello(self):
        print('hello, class A')

    def func2(self):
        print('class A: func2')

class B(A):
    def __init__(self):
        A.__init__(self)
        print("class B")

    def hello(self):
        print('hello, class B')

class C(A):
    def __init__(self):
        A.__init__(self)
        print("class C")

    def hello(self):
        print('hello, class C')

class D(B, C):
    def __init__(self):
        B.__init__(self)
        C.__init__(self)
        print("class D")

if __name__ == "__main__":
    d = D()
    d.hello()

    print(D.mro())

"""
output:
class A
class B
class A
class C
class D
hello, class B
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
"""

If the child class is derived from multiple parent classes, the subclass constructor does not own, in order to inherit, which is the parent class at the top and has its own constructor inherits its constructor.

class A(object):
    def __init__(self):
        print("class A")

    def hello(self):
        print('hello, class A')

    def func2(self):
        print('class A: func2')

class B(A):
    def __init__(self):
        A.__init__(self)
        print("class B")

    def hello(self):
        print('hello, class B')

class C(A):
    def __init__(self):
        A.__init__(self)
        print("class C")

    def hello(self):
        print('hello, class C')

class D(B, C):
    pass

if __name__ == "__main__":
    d = D()
    d.hello()

    print(D.mro())

"""
output:
class A
class B
hello, class B
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
"""

If the child class is derived from more than one parent class, subclass does not own constructor, if not the top of the first parent class constructor, in order to find the sequence inherit the parent class constructor after.

class A(object):
    def __init__(self):
        print("class A")

    def hello(self):
        print('hello, class A')

    def func2(self):
        print('class A: func2')

class B(A):

    def hello(self):
        print('hello, class B')

class C(A):
    def __init__(self):
        A.__init__(self)
        print("class C")

    def hello(self):
        print('hello, class C')

class D(B, C):
    pass

if __name__ == "__main__":
    d = D()
    d.hello()

    print(D.mro())

"""
output:
class A
class C
hello, class B
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
"""

2, multiple inheritance search order

Attribute class __mro__or method MRO () can be printed out in the order of succession class, Super () to find a listing MRO, when executed, the class list to find the current position of a lower class.
In order to achieve inheritance, Python will start looking from left to right on the MRO base class list until you find the first match class property.
In Python 3.x, whether or not explicitly specified in the inherited object, all classes are the new class, in the case of multiple inheritance, Classic order to find the parent class property or method is depth-first, look for the new class of the parent class property order is breadth-first.
It is a super class of the MRO. Full MRO Method Resolution Order, the order of succession of the representative class. For each class definition, Python accounting method of calculating a resolution order (MRO) list, MRO simple linear list is a sequential list of all the base classes.
MRO list structure is achieved by a linear algorithm C3, MRO MRO merges a list of all the parent class and follow the following three criteria:
A, sub-class will first be examined in the parent class.
B, multiple parent classes are checked in accordance with their order in the list.
C, if there are two legal option for the next class, selecting a first parent.
MRO can ensure that multiple inheritance happens only once per class, super (). Init with respect to the class name .init, on the use of single inheritance almost no difference, but in the multiple inheritance, super method to ensure that each parent class's method only once, and the class name of the method causes the method to be executed multiple times.
When single inheritance, the use of super methods, not all pass, pass only the required parameters parent class method, otherwise it will error; when multiple inheritance, class name .init method requires each parent to write all over again, while the use super method only one statement will execute all the methods of the parent class, multiple inheritance and therefore need to pass all parameters.
Nine, class polymorphism
Polymorphism is usually achieved by way of inheritance interface, no interface in Python, but Python can be thrown by a member of the body of a method to force a NotImplementedError abnormal subclass inherits the interface must implement the interface method before calling an interface method .

class Animal(object):  # Animal Interface
    def __init__(self, name):
        self.name = name

    def walk(self):
        raise NotImplemented('Subclass must implement the abstract method by self')

    def talk(self):
        raise NotImplemented('Subclass must implement the abstract method by self')

class Dog(Animal):
    def talk(self):
        print('%s is talking:wang wang...' % self.name)

    def walk(self):
        print('%s is a Dog,walk by 4 legs' % self.name)

class Duck(Animal):
    def talk(self):
        print('%s is talking: ga ga...' % self.name)

    def walk(self):
        print('%s is a Duck,walk by 2 legs' % self.name)

if __name__ == "__main__":
    dog = Dog('Trump')
    dog.talk()
    dog.walk()

    duck = Duck('Tang')
    duck.talk()
    duck.walk()

"""
output:
Trump is talking:wang wang...
Trump is a Dog,walk by 4 legs
Tang is talking: ga ga...
Tang is a Duck,walk by 2 legs
"""

All subclasses interfaces of all the methods defined in the interface must be implemented; subclasses interfaces each interface when implemented in the same way to achieve specific code is different, i.e. polymorphic.

Ten, reflection

Python is reflected by the mechanism hasattr, getattr, setattr, delattr four built-in functions implemented four built-in functions may be used not only in classes and objects, it can also be used in the module.
hasattr (key) returns a bool value is determined in the absence of a member of the class or attribute or object.
getattr (key, default = xxx) members or obtain attribute class or object, and if not, it will throw an exception AttributeError, if you define the default so when there is no property will return the default value.
setattr (key, value) if there is a key attribute, then update key attributes, if not add the key attribute and assign value.
delattr (key) to delete an attribute.
Example code:

import uuid

class Person(object):
    nationality = "China"

    def __init__(self, name):
        self.name = name
        self.__id = str(uuid.uuid1())

    def hello(self):
        print("Hello, I am %s, I come from %s, My ID is %s" %(self.name, self.nationality, self.__id))

if __name__ == "__main__":
    bauer = Person("Bauer")
    setattr(bauer, "sex", "Man")
    print(getattr(bauer, "name"))
    print(getattr(bauer, "nationality"))
    print(getattr(bauer, "sex"))
    helloFunc = getattr(bauer, "hello")
    helloFunc()
    if hasattr(bauer, "job"):
        print(getattr(bauer, "job"))
    delattr(bauer, "sex")
    print(getattr(bauer, "name"))
    print(getattr(bauer, "nationality"))
    print(getattr(bauer, "sex"))  # AttributeError: 'Person' object has no attribute 'sex'

XI singleton

In object-oriented programming, is a single-mode embodiment only one object class, all operations are done by singletons, codes are as follows:

class Instance:
    __instance = None

    @classmethod
    def get_instance(cls):
        if cls.__instance:
            return cls.__instance
        else:
            cls.__instance = Instance
            return cls.__instance

obj1 = Instance.get_instance()
print(id(obj1))

obj2 = Instance.get_instance()
print(id(obj2))

# output:
# 35307304
# 35307304

Twelve, exception handling

1, exception handling Introduction

Python try except finally used in combination to achieve capture abnormal, the except Exception in all abnormal parent, exemplary exception handling as follows:

try:
    int("12a")  #可能出现异常的代码
except IndexError as e:  # 捕捉索引异常的子异常
    print("IndexError:",e)
except ValueError as e:  # 捕捉value错误的子异常
    print("ValueError:",e)
except Exception as e:  # 使用Exception捕获,Exception能够捕获所有的异常
    print("Exception:",e)
else:  # 如果没有异常发生,执行else中的代码块
    print("true")
finally:  # 不管是否发生异常,在最后都会执行finally中的代码,假如try里面的代码正常执行,先执行else中的代码,再执行finally中的代码
    print("finally")

2, a custom exception handler

Exception is the parent class for all exceptions, can customize Exception subclass, implement a custom exception handling.

class TypeErrorException(Exception):
    def __init__(self, message):
        self.message = message

    def __str__(self): # 打印异常的时候会调用对象里面的__str__方法返回一个字符串
        return self.message

if __name__ == "__main__":
    try:
        raise TypeErrorException("Type error")
    except TypeErrorException as e:
        print("TypeErrorException:",e)
    except Exception as e:
        print("Exception:",e)
    else:
        print("true")
    finally:
        print("finally")

3, affirm

Assertion assert generally used in the execution environment is determined, as long as the condition is not asserted, throwing an exception, a subsequent code is not executed.

print("Assert test")

ok = True
result = False
assert ok == result

print("Assert test")

# output:
"""
Assert test
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    assert ok == result
AssertionError
"""

Guess you like

Origin blog.51cto.com/9291927/2415493