35.python full Stack Road: Facing the object advanced

Source: Internet
Author: User
Tags true true

Facing the object Advanced 1. Self in multiple inheritance
Class A:    def bar (self):        print (' Bar ') self.f1 (') ' the '        itself ' represents the object of Class D D1D1 if you want to find F1 in his parent class, you should first go to Class C, ' class B (A). :    def F1 (self):        print (' B ') class C:    def F1 (self):        print (' C ') class D (C, B):        PASSD1 = D () D1.bar ()
   Process Analysis:
    1. D1 = D (), finally found the object inside the __init__ method created objects D1
    2. D1.bar (), execute Bar method, first go to C to find, then go to B inside find, finally found in a
    3. Executes the bar method in a, encounters self.f1 (), at which point the self still represents the object D1
    4. Still first go to C inside Find method F1, finally found in C
2. Construction method2.1 General Construction methods
Class Animal:    def __init__ (self):        print (' A constructor method ')        self.ty = ' Animal ' class Cat (Animal):    def __init__ (self) :        print (' B construction method ')        SELF.N = ' cat ' a = Animal () c = Cat () print (a.__dict__) print (c.__dict__) ' A constructor method B construction method {' Ty ': ' Animal '} {' n ': ' Cat '} '
   2.2 If we want the parent class's field Ty to encapsulate the object created by the subclass cat?
Class Animal:    def __init__ (self):        print (' A construction method ')        self.ty = ' Animal ' class Cat (Animal):    def __init__ ( Self):        print (' B construction method ')        SELF.N = ' Cat '        self.ty = ' Animal '        # constructor method for executing parent Class A = Animal () c = Cat () print (a.__dict__) Print (c.__dict__) ' A construction Method B construction Method {' Ty ': ' Animal '} {' n ': ' Cat ', ' ty ': ' Animal '} '
   2.3 If the parent class has a large number of fields, you want to inherit these fields when you create the subclass, and you need to repeat the code very much

We can do the construction of the parent class Super

Class Animal:    def __init__ (self):        print (' A construction method ')        self.ty = ' animal '        Self.chi = ' eat '        self.he = ' Drink '        self.la = ' Pull ' # method 1class Cat (Animal):    def __init__ (self):        print (' B construction method ')        SELF.N = ' cat '        super (cat, Self). __init__ ()  # Find the Cat's parent class and execute the constructor of its parent class method 2class Cat (Animal):    def __init__ (self):        print (' B constructor method ')        SELF.N = ' Cat '        Animal.__init__ (self) "a = Animal () c = Cat () print (a.__dict__) print (c.__dict__)" A construction Method B construction Method A construction method {' Ty ': ' Animal ', ' chi ': ' Eat ', ' he ': ' Drink ', ' la ': ' pull '} {' n ': ' Cat ', ' ty ': ' Animal ', ' chi ': ' Eat ', ' he ': ' Drink ', ' la ': ' Pull ' '
3. Face reflection in the object3.1 Basic Usage
Class Foo:    def __init__ (self, name):        The field of the # class        Self.name = Name    def show (self):        print (' show ') obj = Foo (' Alex ') # Through the class, find the method of the class R1 = hasattr (Foo, ' Show ') print (R1) ' True ' # through the object, you can find either the members of the object, or the members of the class r2 = hasattr (obj, ' name ') c5/># find the member of the object R3 = hasattr (obj, ' show ')  # through the class object pointer, you can find the method of the class print (R2, R3) "" True True "
   3.2 Using the character import module to manipulate members of the class with reflection
class Foo:     def __init__ (self, name):         # Fields of the class        Self.name = name    def  Show (self):        print('  Show')
testmoudle.py
# import Module by string c = __import__ (' Testmoudle ', fromlist=true)  # The module name has nested words # by reflection get the class in the module class_name = GetAttr (c, ' Foo ') # Create an object from the class obj = Class_name (' Alex ') # Gets the value of name by reflection val = getattr (obj, ' name ') print (val) "Alex"

  

4. Members of the classmember:

Fields: Normal fields ( data for each object are different ), static fields ( each object has one copy )

Methods: Common methods ( using data encapsulated by Objects ), static methods ( without using object Encapsulation ), class methods ( automatically passing in the class name )

Attributes: Calling a method as a field

   quick judgment is performed by the class or by the object:

    withSelf, the object is called

    Noself, class invocation

Class Province: # static field country = ' China ' def __init__ (self, name): # normal field self.name = name # Self.country = ' China ' # normal method def show (self): print (' Show ') # class method @classmethod def xxoo (CLS): # CL        s = = class print (' Xxoo ') # static method @staticmethod def XO (Arg1, arg2): Print (' XO ') def start (self):  temp = '%s sb '% self.name return Temp # attribute, forged method into field, used to get @property def end (self): temp = '%s ' SB '% self.name return temp @end. Setter def end (self, value): print (value) Hebei = Province (' Hebei ') provi Nce.xo (1, 2) # method that requires parentheses to access # @property can be accessed by accessing the field in the way obj = Province (' alex ') Ret1 = Obj.start () Ret2 = Obj.endprint (Ret1, Ret2) # Get Field # print (obj.name) # set field # Obj.name = ' 123 ' # print (obj.name) print (obj.end) # Get obj.end = 123 # set "' ************ spec 1. Access by class: Static field, static method, class method (special form of static method) Province.country Province.xo (1, 2) 2. Access by object: Normal field, class method hebei.na Me Hebei.show () *******Specification **************3. The meaning of static fields the existence of each object is only one copy in the class. 4. The meaning of the static method the normal method needs to create an object before executing it. Static methods do not need to create objects first, similar to a normal function In the class, which is useful in C # and Java because they can only object-oriented, you must create Class 5. class methods and static methods can only be distinguished by a static method through class access, and the class name of the current class is automatically obtained by any class method of the parameter. , passed in as a parameter "'

  

5. Member Modifiers

  For private, only you can access, others (including subclasses) cannot access

   5.1 for Fields
Class Foo:    A = ' AA '    __a = ' AA '    def __init__ (self):        self.name = ' Alex '        self.__name = ' Wuwen '    def AAA (self):        print (foo.__a)        print (self.__name)    def BBB (self):        passclass Bar (Foo):    def Fetch (self):        print (self.__name) # static field print (FOO.A)   # Common in class outside class is accessible #print (foo.__a) obj = Foo ()    # Private can only access in class OBJ.AAA () # Normal field print (Obj.__name)  # cannot be accessed externally obj.aaa ()  #  can be accessed externally obj1 = Bar ()  #  constructor method for executing parent class print (Obj.__name)  # inherited subclasses cannot access Obj1.fetch () # Cannot access  obj1.aaa () #    cannot access
  5.2 for methods
Class Foo:    def __init__ (self):        pass    def __aaa (self):        print (' aaa ')    def BBB (self):        self.__ AAA ()    @staticmethod    def __eee ():        print (' ddd ')    @staticmethod    def FFF ():        foo.__eee () # Normal method obj = Foo () #obj. __AAA ()  # cannot directly access obj.bbb ()     # Indirect Access # static method # foo.__eee () # static method external through class cannot access foo.fff ()     # Static methods for indirect access to private # class methods and attributes are the same
   5.3 Python differs from other languages by forcibly accessing private members

    Object. _ Class + Private member

Class Foo:    def __init__ (self):        self.name = ' Alex '        self.__name = ' Wuwen '    def aaa (self):        print (self.__name)    def BBB (self):        passobj = Foo () # Obj.__name  cannot directly access print (Obj._foo__name)  # forcibly access ' Wuwen '

  

6. Special members of the class

__init__

__del__

__call__

__getitem__

__setitem__

__delitem__

__new__

__metaclass__

   6.1 For some operations of the dictionary, why objects created by Dict can use shortcut keys such as [], del to manipulate the object

__init__

__getitem__

__setitem__

__delitem__

# dic = Dict (k1=123, k2=456)  because there are __init__ methods in the DIC class # print (dic[' K1 '))  Why objects can be added []  because there are __getitem__ methods in the DIC class # DIC [' k1 '] = 456   Because there are __setitem__ methods in the DiC class # del dic[' K2 ')     because the DIC class has the __delitem__ method class Foo:    def __init__ (self):        print (' init ')    def __call__ (self, *args, **kwargs):        print ("call")    def __getitem__ (self, item):        print (item)    def __setitem__ (self, Key, value):        print (key, value)    def-__delitem__ (self, key):        print (' simulation deleted successfully!! ') obj = Foo () obj ()  # Object followed by () Execute __call__obj[' "]  # object plus [] Execute __getitem__obj[' []] = 77del obj[' 77" " initcall6677 77 "
   6.2 for the list, how is his slicing operation implemented in the class?

    __getitem__

R = List ([One, one, one, one, one, one, and all]) ret = r[1:6:2]  # Slice print (ret) class Foo:    def __getitem__ (self, item):        pri NT (item, type) obj = Foo () obj () obj[1:3]  # When slicing, pass 1:3 into a slice class to get an object and then pass in GetItem ' slice (1, 3, None) <class ' Slice ' > '
   6.3 __dict__
Class Foo: "I am the annotation of the Class" "Def __init__ (self): Self.name = ' alex ' Self.gender = ' Female ' def _  _call__ (self, *args, **kwargs): Print ("call") def __getitem__ (self, item): Print (item, type (item)) def __setitem__ (self, Key, value): Print (key, value) def __delitem__ (self, Key): print (' simulated delete succeeded!! ') obj = Foo () print (obj.__dict__) # View the object encapsulated field ' ' {' name ': ' Alex ', ' gender ': ' Female '} ' Print (foo.__dict__) # View the members of the class ' ' {'  __module__ ': ' __main__ ', ' __doc__ ': ' \ n I am the comment of the class \ n ', ' __init__ ': <function foo.__init__ at 0x000000000220ba60> ' __call__ ': <function foo.__call__ at 0x000000000220bae8>, ' __getitem__ ': <function Foo.__getitem__ at 0x000000000220bb70>, ' __setitem__ ': <function foo.__setitem__ at 0x000000000220bbf8>, ' __delitem__ ': < function foo.__delitem__ at 0x000000000220bc80>, ' __dict__ ': <attribute ' __dict__ ' of ' Foo ' objects>, ' __ weakref__ ': <attribute ' __weakref__ ' of ' Foo ' objects>} '‘‘ 
   6.4 Similar to string, list, why can we use for loop this object?

    In fact: The __iter__ method in the default execution class if the For loop object is a generator

So an object can be used for loops, indicating that the object has a __iter__ method in its class.

Li = [1, 2, 3]  #  equivalent to Li = List ([]) for I in Li:    print (i) ' 123 ' "# Implements a simple version of the List class class Foo:    def __iter__ (s ELF):        yield 1        yield 2        yield 3li = Foo () for I in Li:    print (i) ' 123 '
   6.5 __new__ and __metaclass__

        

35.python full Stack Road: Facing the object advanced

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.