Python object-oriented advanced programming

Source: Internet
Author: User

Dynamic binding of properties and methods in Python

Class Student (object): Pass # instantiates an object s = Student () # Binds an attribute to this object names.name = ' john ' Print (s.name) John # defines a method def SE T_age (self, age): Self.age = Age # import module from types import methodtype #给s这个对象绑定一个set_age的方法s. Set_age = Methodtype (set  _age, s) s.set_age = 30s.age25 # The method that binds the instance object is valid only for that instance. # The practice of binding methods to all instances is to give the class binding method Def Set_score (self, score): Self.score = score Student.set_score = Methodtype (Set_score, Stud ENT) # When you bind a method to a class, all instances can be called

__slots__ variables in python

The function of the __slots__ variable is to restrict the properties that the class instance can add:

Class Student (object): __slots__ = (' name ', ' age ')

Only the name and age properties can be dynamically bound when creating an student instance.

The properties defined by __slots__ only work on the current class instance and do not work on inherited subclasses.



Python's @property Decorator

@property is a python built-in decorator, and its role is to turn a method into a property access.

class student (object):     @property      def score (self):         return self._score      @score. Setter    def score (Self, value):         if not isinstance (Value, int):             raise valueerror (' score must be an  integer! ')         if value<0 or value>100:             raise valueerror (' score must  between 0 ~ 100! ')         self._score = value 
s = Student () S.score = 60 # actual conversion to S.set_score S.score # actual conversion to S.get_score () 60


Only the Getter method is defined, and the setter method is not defined as a read-only property

Class Student (object): @property def Birth (self): return Self._birth @birth. Setter def birth (self, Valu E): Self._birth = value @property def age (self): return 2015-self._birth

Birth has read and write, age is readonly



Multiple inheritance of Python

Class Animal (object): Passclass mammal (Animal): Passclass Bird (Animal): Passclass Dog (mammal): Passclass Bat (M Ammal): Passclass Parrot (Bird): Passclass Ostrich (Bird): Passclass Runnable (object): Def run (self): PRI NT ("Running ...") class Flyable (object): Def Fly (self): print ("Flying ...")

Multiple Inheritance of classes

Class Dog (Mammal, Runnable): Passclass Bat (Mammal, flyable): Pass


The mixin in Python

Mixin's role is to better see the inheritance relationship, the purpose is to add multiple functions to a class, so in the design class, we have limited consideration through multiple inheritance to combine the functions of multiple mixin, rather than design multi-layered complex inheritance relationship.


Examples of Python's own library using mixin:

Tcpsserver and Udpserver must use a multi-process or multithreaded model to serve multiple users at the same time. Both of these models are provided by Forkingmixin and ThreadingMixIn.


TCP Services for multiple processes:

Class Mytcpserver (TCPServer, forkingmixin): Pass


Multi-threaded UDP service:

Class Myudpserver (Udpserver, threadingmixin): Pass


More advanced co-process model, write a coroutinemixin:

Class Mytcpserver (TCPServer, coroutinemixin): Pass




Python Custom class

Class Student (object): Def __init__ (self, name): Self.name = name def __str__ (self): return ' S Tudent Object (name:%s) '% Self.name
Print (Student (' Michael ')) Student object (Name:michael)
s = Student (' Michael ') s0x345ldf05d


The direct display variable is called not __str__ (), but __repr__ ().

The difference between __str__ () and __repr__ () is that __str__ () returns the string that the user sees, and __repr__ () returns the string __repr__ () that the program developer sees as a debug service.

Class Student (object): Def __init__ (self, name): Self.name = name def __str__ (self): return ' Stu Dent Object (name=%s) '% self.name __repr__ = __str__


A class wants to be used in a for loop, must implement a __iter__ () method, return an iterative object, and the for loop will constantly call the Iteration object's __next__ () method to get the next value of the loop, Until Stopiteration exits the loop.

Class Fib (object): Def __init__ (self): self.a, self.b = 0, 1 def __iter__ (self): return self def __next__ (self): SELF.A, self.b = self.b, SELF.A + self.b if SELF.A > 100000:raise stopiteration () return sel F.afor N in Fib (): Print (n) 11235...46368


If you want to take an element out of a class as a list, you need to implement the __getitem__ () method:

Class Fib (object): Def __getitem__ (self, N): A, B = 1, 1 for x in range (n): A, B = B, a+b Return a

If this class implements the __getitem__ () method, the class can be manipulated as a list, but the type of the arguments passed in by the __getitem__ () method needs to be judged. The parameter may be an int, or it may be a slice object slice. This parameter needs to be judged.

Class fib (object):     def __getitem__ (self, n):         if isinstance (N, int):             a, b = 1, 1             for x in range (n):                 a, b = b, a+b             return a        if  Isinstance (n, slice):             start =  n.start            stop = n.stop             if start is None:                 start = 0             a, b = 1, 1             L = []             for x in range (stop):                 if x >= start:                     l.append (a)                  a, b = b,  a+b            return l
f = Fib () f[0:5] [1,1,2,3,5] f[:10] [1,1,2,3,5,8,13,21,34,55]

Make a judgment on the parameters of a __getitem__ () method. And do other work on this. The processing of the step, the treatment of negative numbers, and so on.


__GETATTR__ (): The method dynamically returns an attribute.

When calling a nonexistent property, Python attempts to invoke __getattr__ (self, ' score ') to try to get the property.


The __call__ () method is called directly on the instance itself and is invoked directly on the instance.

Class Student (object): Def __init__ (self, name): Self.name = name def __call__ (self): print ("My name I S%s. "% self.name) s = Student (' Michael ') s () My name is Michael.

__CALL__ () defines the parameter.

Determine if a variable is an object or a function, and more often we determine whether an object can be called. The object that can be called is a callable object.



Enumeration classes for Python

Define an enumeration class:

from enum Import enummonth = enum (' Month ', (' Jan ', ' Feb ', ' Mar ', ' April ', ' may ', ' June ', ' Jul ', ' April ', ' Sep ', ' Oct ', ' Nov ', ' Dec '))

Enumeration classes are used:

Use Month.jan directly to refer to a constant, or enumerate all its members.

For name, member in Month.__members__.items (): Print (name, ' = = ', member, ', ', Member.value)
form enum Import enum, Unique@uniqueclass Weekday (enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6

@unique Adorner guarantees no duplicate values.



Python uses meta-classes

The type () function can see the types of a type or variable, and can also create a new type.

Creating a Class object through the type () function requires passing 3 parameters:

    1. The name of the class.

    2. Inherits the collection of parent classes, noting the multiple inheritance of Python.

    3. Class's method name and function binding,

DEF fn (self, name= ' world '): print (' Hello ',%s. '% name) Hello = Type (' Hello ', (object,), Dict (HELLO=FN)) H = Hello () H. Hello () print (Type (Hello)) print (Type (h))


The function of Metaclass is to control the creation behavior of the class.

If we want to create a class, we must create a class based on Metaclass, define Metaclass first, and then create the class.

Metaclass allows you to create classes or modify classes

Instances used by the Meta class:

# Metaclass is a template for a class, so you must derive from the ' type ' type: Class Listmetaclass (type): Def __new__ (CLS, name, bases, attrs): attrs[' add ' = Lambda Self, value:self.append (value) return type.__new__ (CLS, name, bases, Attrs)

With Listmetaclass, when we define the class, we want to instruct the class to be customized with Listmetaclass, passing in the keyword parameter metaclass:

Class MyList (list, metaclass=listmetaclass): Pass

To create the MyList class by listmetaclass.__new__ (), we can modify the definition of the class, add a new method, and return the modified definition.

The parameters that are received by the __new__ () method are:

    1. Object of the class currently being prepared for creation

    2. The name of the class

    3. A collection of class-inherited parent classes

    4. Collection of methods for the class


In general, you will not encounter metaclass, and when using ORM, you will always encounter the need to modify the class definition by Metaclass.

Orm--object relational mapping, object-relational mapping. is to map a row of a relational database to an object, that is, a class that corresponds to a table, so that the code is easier to write without having to manipulate the SQL statement directly.

To write an ORM framework, all classes can only be defined dynamically, because only the user can define the corresponding class based on the structure of the table.

A simple example of an ORM framework:

Class User (Model): # Defines the property of the class to the column mapping id = integerfield (' id ') name = Stringfield (' username ') email = Stringfield (' E Mail ') password = Stringfield (' password ') # creates an instance of U = User (id = 123, name= ' Michael ', email= ' [email protected] ', pass word= ' My-pwd ') # Save to Database U.save ()

Follow the above interface to implement the ORM

Class Field (object): Def __init__ (self, Name, column_type): self.name = name Self.column_type = column_ty PE def __str__ (self): return ' <%s:%s> '% (self.__class__.__name__, self.name)

Define various types of field

Class Stringfield (Field): Def __init__ (self, name): Super (Stringfield, self). __init__ (name, ' varchar ') class Integerfield (Field): Def __init__ (self, name): Super (Integerfield, self). __init__ (name, ' bigint ')








Python object-oriented advanced programming

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.