1. Introduction
(1) class and instance: class is the definition of object, instance is "real kind".
Definition class: The class name is usually preceded by a capital letter.
Class Mynewobjecttype (Bases):
' Define Mynewobjecttype class '
class_suite
Bases can be one (single inheritance) or multiple (multiple inheritance) for inherited parent classes.
Object is the "mother of all Classes".
Python invokes the class for instantiation, instantiating the class without using the new keyword.
>>>c=mynewobjecttype ()
A class can sometimes be used only as a namespace.
Class MyData (object):
pass
mathobj=mydata ()
mathobj.x=4
mathobj.y=5
These properties are dynamic and do not need to be declared or assigned to them in the constructor or anywhere else.
(2) method
Define methods: Properties and methods use hump notation.
Class Mydatawithmethod (object):
def printfoo (self):
print ....
All methods exist self, which represents the instance object itself.
A static method or class method does not require self.
The __init__ () method is similar to a constructor, but is different from a constructor because Python is not new. After the instance is created, the method is invoked before the instantiation call returns the instance.
2, object-oriented programming Common terminology abstract/implementation: Modeling reality Encapsulation/Interface synthesis: union, aggregation inheritance/derivation generalization/special polymorphism introspection/reflection
3, Class
in Python, everything is an object.
The following is the definition syntax for the class.
Class ClassName (object):
' class documentation string '
Class_suite
Python does not support pure virtual functions (like C + +) or abstract methods.
Workaround: Throws a Notimplementederror exception in the base class method.
4. Class Attributes
(1) Property
Property (data or function), which is accessed using the period property identifier.
The property itself is also an object and has its own properties, so accessing the property creates a chain of attributes.
(2) class attribute/Instance Data property
Instance properties are used most in OOP, and class properties become useful only when there is a need for more "static" data types, regardless of any instance, and methods are class properties.
Python requires that there is no instance and the method cannot be invoked. Method must be "bound" to an instance to be invoked directly. The unbound method may be invoked, but the instance object must be explicitly given in order to ensure that the call succeeds. However, regardless of binding, the method is the intrinsic property of the class in which it resides, even though they are almost always invoked through an instance.
(3) methods to determine what attributes of a class use the built-in function dir () to access the dictionary properties of the class __dict__ the built-in function VARs () to accept the class object as a parameter, returning the contents of the __dict__ property of the class.
(4) Special class attributes C.__name__ Class C's name (string) c.__doc__ Class C's document string c.__bases__ all the parent classes of Class C, the tuple c.__dict__ Class C, and the module (C.__MODULE__) where Class C is located 1.5 instance C corresponding Class (new Class)
5. Example
The classes and types are unified in Python 2.2.
Python creates an instance by calling a class object.
①__init__ () method
When the class is invoked, the instance object is created, and after the object is created, the __init__ () method is called to complete the special operation, the returned class object is executed, and the instantiation is finished.
Python does not create an instance with new, there is no constructor defined, and the object is created by Python.
②__new__ () method
Constructor method, __new__ () is more like a real constructor than the __init__ () method, because __new__ () must return a valid instance, which is passed to the __init__ () method as self.
The __new__ () method invokes the __new__ () method of the parent class to create the object.
The __new__ () method can instantiate an immutable object when deriving from an internal type.
③__del__ () method
The destructor method, which is used to perform special processing before the instance is released, when all references to the instance object are cleared. The __del__ () method can only be invoked once. Using the __del__ () method, do not forget to invoke the __del__ () method of the parent class first. Del X does not indicate that the x.__del__ () method is invoked and only the reference count is reduced. If there is a circular reference, the __del__ () method of the object may never be executed. Exceptions that are not caught by the __del__ () method are ignored, and the __del__ () method is not implemented unless necessary. If the __del__ () method is defined and the instance is part of a loop, the garbage collector will not terminate the loop and you will need to explicitly call Del.
6. Instance Properties
method is strictly a class attribute. Instance only has data properties.
(1) Instantiate instance property
① Sets the instance property in the __init__ () method.
Setting the properties of an instance can take place at any time after the instance is created. The __init__ () method is one of the key points for setting these properties. Python can create instance properties at run time (one of Python's outstanding features)
② Default parameters provide the default instance installation.
Class Hotelroomclac (object):
def __init__ (self,rt,sales=0.085,rm=0.1):
self.salestax=sales
SELF.ROOMTAX=RM
Self.roomrate=rt
The ③__init__ () method should return none
The __init__ () method should not return any objects because the instance object is automatically returned after the instantiation call.
(2) View instance Properties View Instance properties: Dir (), __dict__ property, VARs () Special instance properties: i.__class__, i.__dict__ built-in type properties: The built-in type can use the Dir () method, and you cannot access __ DICT__ Special properties, because this property does not exist in an builtin type.
(3) class and instance properties (similar to automatic variables and static variables)
Class properties can be accessed using classes, which can also be accessed with instances that have no properties of the same name.
Class properties can be accessed through classes or instances, but you can only use classes to access class properties to update the values of class properties. Updating a class property in an instance creates an instance property with the same name and "obscures" the class attribute. Class properties work When you delete an instance property with the same name. Therefore, it is prudent to access class properties from the instance.
Class C (object): #定义类
Version = 1.2# static member
>>>c=c ()
>>>c.version #通过类来访问
>> >c.version #通过实例来访问
>>>c.version+=0.1 #通过类 (only) to update class attributes
>>>c.version = 1.3 # Any assignment to an instance property creates an instance property rather than an update of the class property
When a class property is a mutable type, the instance property is not created, and the direct action is the Class property.
Class Foo (object):
x={2003: ' Poe2 '}
>>>foo=foo ()
>>>foo.x[2004]= ' valid path '
>>>foo.x
{2003: ' poe2 ', ' Valid path '}
>>>foo.x
{2003: ' poe2 ', ' valid ' Path '} #生效了
>>>del foo.x #删除会报错, because there is no shadowing so it cannot be deleted
(4) class attribute persistence
Class attribute, which, despite the progress of the entire instance (and its properties), is ignored (and therefore independent of the instance), and the modification of the class attribute affects all instances. The class attribute is a static member.
7, binding and method calls
(1) Binding
A method is simply a function defined within a class, meaning that the method is a class property rather than an instance property.
Method can be invoked only if the class has an instance. method is considered to be bound to an instance. The variable self in a method represents an instance object that calls this method.
(2) method call
① calls unbound methods (uncommon): The class is not yet instantiated.
Class Empladdrbookentry (addrbookentry):
' Employee Address Book Entry class '
def __init__ (self,nm,ph,em):
addrbookentry.__init__ (self,nm,ph) #覆盖父类方法
Self.empid=em
② Call binding method: Class has been instantiated.
>>>mc=myclass ()
>>>mc.foo ()
Summary : A method is defined within a class, is a class method, a method is bound to an instance, invoked by an instance, unbound, and called by a class.
8. Static method and class method (2.2)
(1) Examples of creating static methods and class methods in classic classes
Class Teststaticmethod:
def foo ():
print ' calling static method foo () '
foo=staticmethod (foo) # Built-in functions, converting methods to static methods
class Testclassmethod:
def foo (CLS): #cls为类对象, similar to self
print ' calling class Method foo () '
foo=classmethod (foo) #内建函数, converting methods to class methods
These functions can be called through classes or instances.
>>>tsm=teststaticmethod ()
>>>teststaticmethod.foo ()
>>>tsm.foo ()
> >>tcm=testclassmethod ()
>>>testclassmethod.foo ()
>>>tcm.foo ()
(2) Examples of using function modifiers to create static methods and class methods (2.4)
Class Teststaticmethod:
@staticmethod
def foo ():
print ' calling static method foo () '
class Testclassmethod:
@classmethod
def foo (CLS):
print ' Calling class Method Foo () '
9. Inherit
(1) through the inheritance coverage method
When a subclass defines the same method as the base class, it overrides the (override) base class method.
Subclasses can call the base class method using methods that call unbound base-class methods.
You can also call the base class method using the super () built-in method.
When derived from a class with a constructor __init__ (), if you do not overwrite __init__ (), it will be inherited and automatically invoked, but if you overwrite __init__ () in subclasses, the __init__ () of the base class will not be invoked automatically if the subclass is instantiated. To invoke the __init__ () method of the parent class, you need to use super ().
(2) deriving from a standard type
In classic classes, you cannot subclass a standard type.
After 2.2, you can subclass the standard type.
Subclass Python Type: One is a mutable type, and the other is an immutable type.
① invariant type of subclass
Class Roundfloat (float):
def __new__ (cls,val): Return
float.__new__ (Cls,round (val,2))
All __new__ () methods are class methods, so explicitly passing in the class as the first argument.
Class Roundfloat (float):
def __new__ (cls,val): Return
Super (ROUNDFLOAT,CLS). __new__ (Cls,round (val,2))
The super () built-in function is typically used to capture the corresponding parent class to invoke its __new__ () method.
② variable type of subclass
Class Sortedkeydict (Dict):
def keys (self): return
sorted (super (sortedkeydict,self). Keys ())
(3) Method interpretation Order (MRO) in multiple inheritance
2.2, the algorithm is simple: depth first, from left to right to search, to obtain the attributes used in the subclass. Multiple inheritance takes the first name found.
2.2 Proposed new MRO, algorithm idea is based on the inheritance structure of each ancestor class compiled a list, including the search to the class, by policy delete duplicates.
2.3 Use the new C3 algorithm to replace, take breadth first.
New classes have __mro__ attributes that tell you the search order.
New classes that use the classic class MRO will fail.
Diamond Effect
Using the Classic class MRO, when the D is instantiated, the result of the object.__init__ () is no longer obtained by c.__init__ (). With the new class, the base class needs to appear, so that in the inheritance structure, a diamond is formed.
Supplemental : Document strings are not inherited from the base class. Because document strings are unique to classes, functions/methods, and modules.
10. Built-in functions for classes, instances, and other objects
(1) issubclass ()
Boolean function that determines that a class is a subclass or descendant class of another class (a class can be considered a subclass of itself).
Issubclass (Sub,sup)
Starting with 2.3, the second argument can be a tuple of possible parent classes. It returns true as long as the sub is a subclass of any of them.
(2) isinstance ()
Boolean function that determines whether an object is an instance of another given class.
Isinstance (OBJ1,OBJ2)
Obj1 is an instance of Obj2, or an instance of a subclass of Obj2, returns True.
Starting from 2.2, OBJ2 can be a tuple, and obj1 returns True if it is an instance of any candidate type or class in the Obj2 tuple.
(3) hasattr (), GetAttr (), SetAttr (), delattr ()
The *attr () series functions work on a variety of objects, not just classes and instances.
*attr (obj, ' attr ' ...) is equivalent to operating obj.attr.
Hasattr () Boolean function that determines whether an object has a specific attribute.
GetAttr (), SetAttr () the properties that are obtained and assigned to the object accordingly. GetAttr () throws a Attributeerror exception when you attempt to read a nonexistent attribute.
Delattr () deletes the attribute.
(4) dir ()
Can be used for instances or classes or modules. For instance, display instance variables, and methods and class properties defined in the class in which the instance is located and all its base classes. For classes, displays the contents of the class and the __dict__ of all its base classes, but does not display class attributes defined in the Meta class. For modules, displays the contents of the __dict__ of the module. Dir () Displays the caller's local variable when no arguments are taken.
(5) Super () (2.2)
Help the programmer find the corresponding parent class, and then call the related properties.
Super (Type[,obj]) returns the parent class of type, passing in the obj parameter for the parent class binding. Obj is an instance, Isinstance (Obj,type) must return true; obj is a class or type, and Issubclass (Obj,type) must return true.
Super (Myclass,self). __init__ ()
(6) VARs ()
Similar to Dir (), only the given object argument must have a __dict__ attribute. If the provided object does not have one of these properties, a TypeError exception is thrown.
VARs () returns a dictionary that contains the properties (keys) and values stored in the object __dict__. If no arguments are supplied for VARs (), a Dictionary of attributes (keys) and their values that contain the local namespace is displayed, that is, locals ().
11, with special methods to customize the class
Python special methods can be used to extend the functionality of classes, which can be implemented by simulating standard types; overloading operators.
(1) Special methods used in Python to customize classes
① Basic Custom Type C.__init__ (self[,arg1,...]) builder (with some optional parameters) c.__new__ (self[,arg1,...]) The constructor (with some optional arguments), usually the character output printable by the subclass c.__del__ (self) parser c.__str__ (self) that sets the invariant data type; built-in str () and print statement c.__repr__ (self) String output at run time, built-in repr () and "operator c.__unicode__ (self) Unicode string output: Built-in Unicode () c.__call__ (Self,*args) Represents callable instance c.__nonzero__ ( Self) defines the value of false for object, the built-in bool () c.__len__ (self) length (available for the Class), and the built-in Len ()
② Object (value) comparison C.__cmp__ (Self,obj) object comparison: Built-in CMP () c.__lt__ (self,obj) and c.__le__ (self,obj) less than/less than or equal to: corresponds to < and <= operator c.__gt__ (self, obj) and c.__ge__ (self,obj) is greater than/greater than or equal to: corresponds to > and >= Operators c.__eq__ (Self,obj) and c.__ne__ (self,obj) equals/Not equal to: corresponding ==,!= and < > operator
③ Property c.__getattr__ (self,attr) Get Properties: Built-in GetAttr (), call c.__setattr__ (self,attr,val) Setting property c.__delattr__ (self,attr) only if the property is not found Delete Property c.__getattribute__ (self,attr) Get Properties: Built GetAttr (), always called c.__get__ (self,attr) (descriptor) Get property c.__set__ (Self,attr,val) (descriptor) Set Property c.__delete__ (self,attr) (descriptor) Delete attribute
④ Numeric type: Two-dollar operator c.__*add__ (self,obj) plus: + operator c.__*sub__ (self,obj) minus:-Operator c.__*mul__ (self,obj) Multiply: * operator c.__*div__ (self,obj) except:/Operator c.__* Truediv__ (Self,obj) True except:/Operator c.__*floordiv__ (self,obj) Flooor except://Operator c.__*mod__ (self,obj) modulo/fetch:% operator c.__*divmod__ (self,obj) except and modulo: built-in Divmod () c.__*pow__ (Self,obj[,mod]) Power: Built-in POW (), * * operator
⑤ Numeric type: binary operator c.__*lshift__ (self,obj) left shift:<< operator c.__*rshift__ (self,obj) Right shift:>> operator C.__*AND__ (self,obj) bitwise AND:& operator C. __*OR__ (self,obj) bitwise OR: | operator c.__*xor__ (SELF,OBJ) bitwise with OR: ^ operator
⑥ Numeric type: unary operator c.__neg__ (self) unary negative c.__pos__ (self) unary positive c.__abs__ (self) absolute value, built-in ABS () c.__invert__ (self) bitwise negation, ~ operator
⑦ Numeric type: numeric Conversions c.__complex__ (self,com) into complex (plural), built complex () c.__int__ (self) to int, built int () c.__long__ (self) to long, built in long () c._ _float__ (self) to float, built-in float ()
⑧ Numeric type: basic notation (String) C.__oct__ (self) octal indicates that the built-in Oct () c.__hex__ (self) hexadecimal indicates that the built-in hex ()
⑨ Numeric Type: Numeric compression C.__COERCE__ (Self,num) is compressed into the same numeric type, and built-in coerce () c.__index__ (self) compresses the optional numeric type as an integer (for example, for slicing indexes, etc.) when necessary.
⑩ Sequence Type The number of items in the c.__len__ (self) Sequence c.__getitem__ (self,ind) gets a single sequence c.__setitem__ (Self,ind,val) sets a single sequence element c.__delitem__ (self,ind) Deletes a single sequence element c.__getslice__ (self,ind1,ind2) Gets the sequence fragment c.__setslice__ (self,ind1,ind2,val) Set sequence fragment c.__delslice__ (Self,ind1, IND2) Delete sequence fragment c.__contains__ (self,val) test sequence members: built-in in keyword c.__*add__ (self,obj) concatenation: + operator c.__*mul__ (self,obj) Repeat: * operator c.__ Iter__ (self) to create an iterator: built-in ITER ()
⑪ Mapping Type The number of items in c.__len__ (self) Mapping c.__hash__ (self) hash (hash) function value c.__getitem__ (self,key) Gets the value of the given key (a) c.__setitem__ (self, Key,val) Sets the value of the given key (c.__delitem__) (Self,key) deletes the value of the given key (key) c.__missing__ (Self,key) Given a key if the dictionary does not exist, a default value is provided
(2) Simple customization
Implement init(),str(),repr(), etc.
Print uses the str() method, and the real string object represents the use of the repr() method.
#! /usr/bin/env python
class Roundfloatmanual (object):
def __init__ (self,val):
assert Isinstance (Val, float), \
"Value must be a float!"
Self.value=round (val,2)
def __str__ (self): return
'%.2f '% self.value
__repr__=__str__
(3) numerical customization
Overloading the __add__ () method overloads the (+) operator.
You can also use the __radd__ () method and the __iadd__ () method.
def __add__ (self,other): Return
self.__class__ (self.hr+other.hr,self.min+other.min)
Overwrite the in-place operation and implement an incremental assignment (2.0), such as Iadd() to support Mon+=tue.
(4) Custom iterators
Implement the __ITER__ () and Next () methods in the class to create an iterator.
#! /usr/bin/env python
class Anyiter (object):
def __init__ (self,data,safe=false):
self.safe=safe
Self.iter=iter (data)
def __iter__ (self): return
self
def next (self,howmany=1):
retval=[]
for Eachitem in Range (howmany):
try:
retval.append (Self.iter.next ())
catch stopiteration:
if Self.safe:
break
else:
raise return
retval
12. Privatization
A property in a class is "exposed" by default, and code in the module where the class resides and the module in which the import class resides can be accessed.
(1) Double underline
Python uses a double underline (__) to "confuse" the property and not allow direct access.
The confusing attributes, which precede the name with an underscore and a class name, such as the __num attribute in the Numstr class, are confused, and the identifier used to access the data value becomes self._numstr__num. Obfuscation can prevent conflicts of the same name in the parent class or subclass.
(2) Single underline
Use single underline (_) to achieve simple module-level privatization.
13. Authorization
(1) Packaging
Wrap any type as a core member of a class, so that the behavior of the new object mimics the behavior that already exists in the data type you want, and removes unwanted behavior. Augmented Python is another form of packaging.
(2) Implementation of authorization
Authorization is a feature of the wrapper.
The process of authorization is that all updated functionality is handled by a part of the new class, but the existing functionality is granted to the object's default properties. The key to implementing authorization is to overwrite the __getattr__ () method and include a call to the getattr () built-in function in your code.
Class Wrapme (object):
def __init__ (self,obj):
self.__data=obj
def get (self): return
Self.__data
def __repr__ (self): return
' Self.__data '
def __str__ (self): return
str (self.__data)
def __ Getattr__ (self,attr): Return
getattr (self.__data,attr)
>>>wrappedcomplex=wrapme (3.5+4j)
>>>wrappedcomplex.real
When accessing the real property, the Python interpreter tries to find the name in the local namespace, and if not, searches the class namespace for a class attribute, and if not, the search for the original object starts the authorization request, at which time the __getattr__ () method is invoked, __ The getattr__ () method calls the GetAttr () method to get the default behavior of an object.
Summary : Implement authorization by overwriting the __getattr__ () method.
Authorization can only access properties, special behavior is not allowed. For example, a slice operation on a list that is built into a type, not an attribute, is not authorized to access.
A property can be a data property, or it can be a function or a method. Python all numeric types, only complex numbers have attributes: Data properties and conjugate () built-in methods.
>>>WRAPPEDLIST=WRAPME ([123, ' foo ', 45.67])
>>>wrrapedlist[3] #会抛出AttributeError
At this point, you can use the "cheat" method to access the actual object and its slicing capabilities.
>>>reallist=wrappedlist.get () #get () method to obtain access to the original object
>>>reallist[3]
14, advanced characteristics of the new Class (2.2+)
(1) General characteristics of new class
The unification of types and classes so that Python data types can be subclass. At the same time, all Python built-in "casting" or conversion functions are now factory functions. For example: Int (), long (), float (), complex;str (), Unicode (), list (), tuple (), type ().
In addition, a number of new functions have been added: basestring ();d ICT (), BOOL (), set (), Frozenset (), Object (), Classmethod (), Staticmethod (); super (); Property (), file (). These class names and factory functions not only create new objects for these class names, but can also be used as base classes to subclass types. You can now also use the isinstance () built-in function, which returns True when Obj is an instance of a given type or an instance of its subclass. Isinstance
Old (not as good):
if Type (obj) ==type (0) ...
If Type (obj) ==types.
inttype ... BETTER:
if Type (obj) is type (0)
... Even BETTER:
if Isinstance (obj,int)
... If Isinstance (obj, (int,long)) ...
If type (obj) is int ...
(2) __slots__ class properties
The __dict__ property tracks all instance properties.
Instance Inst, property foo, then Inst.foo is equivalent to inst.__dict__[' foo '.
The dictionary consumes a lot of memory, and for memory considerations, the __slots__ attribute can be used instead of the __dict__.
__SLOTS__ is a class variable that consists of a sequence of objects. Represented by a collection of instance properties of all legitimate identities. Any instance property that attempts to create a name whose name is not in __slots__ will cause an Attributeerror exception. The class definition with the __slots__ property does not have a __dict__ attribute. The purpose of using the __slots__ property is to conserve memory. Using the __slots__ property prevents users from dynamically adding instance properties to their whim.
Class Slottedclass (object):
__slots__= (' foo ', ' Bar ')
>>>c=slottedclass ()
>>>c.foo=
>>>c.xxx= ' Nihao ' #引发AttributeError异常
(3) __getattribute__ () Special method
The Python class has a special method of __getattr__ () that is invoked only if the property cannot be found in the instance or the __dict__ property of the class or ancestor class. __GETATTRIBUTE__ () is similar to __getattr__ (), except that when an attribute is accessed, it can always be invoked without being limited to a situation that cannot be found. In a class that defines both the __getattribute__ () and the __getattr__ () method, unless explicitly invoked from the __getattribute__ () method, or __getattribute__ () Method throws a Attributeerror exception, otherwise the latter is not invoked. If you are going to access the properties of this class or its ancestors in the __getattribute__ () method, you should always call the ancestor class's method of the same name to avoid causing infinite recursion.
(4) Descriptor (the descriptor is a reusable property)
The descriptor is considered to be a proxy representing the property of the object, and it provides a powerful API for the property. When a property is needed, it can be accessed by a descriptor (and, of course, by using the regular Period property flag method to access the property).
__get__ (), __set__ (), __delete__ () Special methods are used to get the value of a property, to assign a property, to delete a property. Classes that cover both __get__ () and __set__ () are called data descriptors. A class that implements the __set__ () method is called a non-data descriptor, or a method descriptor.
The prototype of __get__ (), __set__ (), __delete__ () is as follows: __get__ (Self,obj,typ=none) =>none __set__ (self,obj,val) =>None __ delete__ (self,obj) =>none
The heart of the entire descriptor system is the __GETATTRIBUTE__ () special method, because access to each property invokes this particular method.
For example, given class X and instance x:
Access to instance properties, X.foo by __getattribute__ () into:
Type (x). __dict__[' foo '].__get__ (X,type (x))
Access to the Class property, then none is passed as an object:
x.__dict__[' foo '].__get__ (none,x)
Access to the parent class properties, super (Y,obj). Foo (assuming Y is a subclass of X):
x.__dict__[' foo '].__get__ (obj,x)
Static methods, class methods, properties, and even all functions are descriptors. The only difference between functions in Python is the difference in invocation methods, which are divided into binding and unbound wolves, which can be handled by function descriptors, which determine how to "encapsulate" the function and the object that the function is bound to, based on the type of function, and then return to the calling object. The order of the descriptors is important, with some descriptors higher than others. A descriptor is a class property, so all class attributes have the highest precedence. Priority sorting: Class properties > Data descriptors > Instance properties > Non-Data descriptor > defaults to __GETATTR__ ().
#!
/usr/bin/env python import os Import pickle Class Filedescr (object): saved=[] def __init__ (self,name=none): Self.name=name def __get__ (self,obj,typ=none): If Self.name not in FileDescr.saved:raise at Rributeerror, "%r used before assignment"% self.name try:f=open (self.name, ' R ') val=pickle . Load (f) f.close () return Val except (Pickle. Unpicklingerror,ioerror,eoferror,attributeerror,importerror,indexerror), E:raise AttributeError, "could not re Ad%r "% self.name def __set__ (self,obj,val): F=open (Self.name, ' W ') Try:pickle.du MP (VAL,F) FileDescr.saved.append (self.name) except (Typeerror,pickle. Pickingerror), E:raise attributeerror, "could not pickle%r"% self.name finally:f.close ( def __delete__ (self,obj): Try:os.unlink (self.name) filedescr.Saved.remove (self.name) except