Python Chapter Eighth

Source: Internet
Author: User

I. Object-oriented supplement

Special class Properties:

For any class C, the following is displayed:

Name of c.__name__ class C (String)

Document string for c.__doc__ class C

C.__bases__ all the parent classes of Class C constitute elements (containing a tuple of all the parent classes)

C.__dict__ property of Class C (contains a dictionary consisting of the data properties of the Class)

The module where the C.__MODULE__ Class C is defined (the full name of Class C is ' __main__. C ', if C is in an import module mymod, then c.__module__ equals Mymod)

C.__class__ class for instance C

Instance:

If the class is a data structure definition type, then the instance declares a variable of this type.  An instance is a life-like class. Creates an instance by invoking a class object.

__init__ () "constructor" method (equivalent to a constructor) that checks for the __init__ method when the class invocation is instantiated, and invokes it if any. __init__ should return none

__new__ () ....? What's the difference from upstairs?

__del__ () "destructor" method, which will not execute until all references to the instance object have been erased. The destructor can only be called once, and once the reference count is 0, the object is cleared

Instance properties: Setting the properties of an instance can be done at any time after the instance is created; The built-in function dir () can display class properties or display instance properties.

Special instance properties, arbitrary object I

Class of i.__class__ instantiation I

I.__dict__ I properties, built-in type does not exist __dict__ attribute, built-in type: int float complex ....

class Properties and instance Properties :

Class properties are accessed through the class name, property name, or by the instance name. property name, but class properties can only be updated by the class (immutable objects), if the same property is assigned to this instance

This adds this property to this instance without affecting the class properties.

Static Methods and class methods:

Staticmethod () and Classmethod () built-in functions:

classTeststaticmethod:deffoo ():Print 'calling static method foo ()'Foo=Staticmethod (foo)classTestclassmethod:deffoo (CLS):Print 'Calling class Method Foo ()'        Print 'foo () is part of class:'Cls.__name__Foo=Classmethod (foo) TSM=Teststaticmethod () Teststaticmethod.foo ( )#calling static method foo ()Tsm.foo ()#calling static method foo ()TCM=Testclassmethod () Testclassmethod.foo ( )#Calling class Method foo\n foo () is part of Class:testclassmethodTcm.foo ()#Ibid .

Use function Modifiers:

In addition to using the built-in method above, you can also use the function modifier as follows:

classTeststaticmethod: @staticmethoddeffoo ():Print 'calling static method foo ()'        classTestclassmethod: @classmethoddeffoo (CLS):Print 'Calling class Method Foo ()'        Print 'foo () is part of class:'Cls.__name__TSM=Teststaticmethod () Teststaticmethod.foo ( )#calling static method foo ()Tsm.foo ()#calling static method foo ()TCM=Testclassmethod () Testclassmethod.foo ( )#Calling class Method foo\n foo () is part of Class:testclassmethodTcm.foo ()#Ibid .

Subclasses and derivations:

Create subclasses: The parentheses are the parent class, and if you do not derive from any ancestor classes, you can use object as the name of the parent class.

class Subclassname (Parentclass1[,parentclass2,...]):       ' Optional class documentation string '       Class_suite

__bases__ Class Property: For any subclass, it is a tuple that contains a collection of its parent class. There are no classes for the parent class, their __bases__ property is empty.

Call the parent class method with the same name in the subclass method:

 class  P (object): #   parent class  def   Foo (self):  print   " hi, I am P-foo ()   '  < span> 

Super () Built-in method: Super () can not only find the base class method, but also for us to pass in self, as follows:

class C (P):     def foo (self):        super (C,self). Foo ()   # Call the C base class method to automatically find the base class for C        print  'hi,i am C-foo ()'

Derive from a standard type:

A. Examples of immutable types:

class roundfloat (float):      def __new__ (cls,val):  # __new__ return float in float is covered           .  __new__(Cls,round (val,2))  #   can also return super (ROUNDFLOAT,CLS). __new__ (Cls,round ( val,2))

B. Examples of mutable types:

class sortedkeydict (dict):     def keys (self):         return sorted (super (sortedkeydict,self). Keys ())

c = sortedkeydict ({' Zheng-cai ': ", ' Hui-jun ':", ' Xin-yi ': 2})
>>> C.keys ()
[' Hui-jun ', ' xin-yi ', ' Zheng-cai ']
>>> print [Key for key in C]
[' Zheng-cai ', ' xin-yi ', ' Hui-jun ']

Multiple inheritance:

Python allows a class to inherit multiple base classes, that is, multiple inheritance.

Classic class inheritance uses depth-first, the new class takes a breadth-first look-up attribute, and the new class has a __mor__ property that displays the inherited lookup order.

Built-in functions for classes, instances, and other objects

Issubclass (Sub,sup): Determines whether a class is a subclass of another class or descendant class, if it is true, the second argument can make a tuple of possible parent class, as long as the first parameter is the subclass of any candidate class in the given tuple, it returns true.

Isinstance (OBJ1,CLASS1): Determines whether an object is an instance of another given class. Yes returns True. The second parameter should be a class.

Hasattr () \getattr () \setattr () \delattr ()------Series functions can work under a variety of objects, not limited to classes and instances. Manipulating obj.attr is equivalent to calling *attr (obj, ' attr ') series functions.

classMyClass (object):def __init__(self): Self.foo= 100Myinst=MyClass () hasattr (Myinst,'Foo')#TrueGetAttr (Myinst,'Foo')# -SetAttr (Myinst,'Bar', 200) GetAttr (Myinst,'Bar')# $Delattr (Myinst,'Bar') hasattr (Myinst,'Bar')#False

Dir (): When acting on an instance, the instance variable is displayed, along with the method and class properties defined in the class where the instance resides and all its base classes, and when it is on a class, it displays the contents of the class and all of its base classes __dict__. When acting on a module, the contents of the __dict__ of the module are displayed. When the parameter is not present, the caller's local variable is displayed.

Super (Type[,obj]) function: Helps to find the corresponding parent class and then makes it easy to call related properties; super (Myclass,self). __init__ ().

var () function: similar to DIR ().

Built-in functions for classes, instances, and other objects

Issubclass (Sub,sup) Returns true if the class sub is a subclass of the class sup, and vice versa is False
Isinstance (OBJ1,OBJ2) Returns True if the instance obj1 is an instance of the class Obj2 or obj2 subclass, or obj1 is a obj2 type, and vice versa Fasle
Hasattr (obj,attr) Returns true if obj has an attribute attr (given as a string), and returns false instead
GetAttr (Obj,attr[,default]) Gets the attr property of obj, similar to the return obj.attr, if the attr is not a property of obj, the default value is returned if a default value is provided, or an exception is thrown
SetAttr (Obj,attr,val) Sets the Attr property value of obj to Val, replacing any attribute value that is already pure; otherwise, create the attribute; similar to obj.attr = Val
Delattr (obj,attr) Removes the attribute attr from obj, similar to Del obj.attr
Dir (obj= None) Returns a list of properties of obj, or a property in the local namespace, that is, locals () if no given obj,dir () is present. Keys ()
Super (Type,obj=none) Returns a proxy object that represents the parent class type, and if no obj is passed in, the Super object returned is unbound, and conversely, if it is a type,issubclass (Obj,type) must be true; no isinstance (Obj,type) It must be true.
VARs (Obj=none) Returns a dictionary of the properties and values of obj, if no obj,vars () is given showing a local namespace dictionary, which is locals ()

Python Chapter eighth

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.