Python face question

Source: Internet
Author: User

Directory:

  • Python language Features
  • 1 function parameter passing of Python
      • 2 meta-classes in Python (metaclass)
      • 3 @staticmethod and @classmethod
      • 4 class variables and instance variables
      • 5 python introspection
      • Li>6 Dictionary derivation
      • 7 python single underscore and double underscore
      • 8 string formatting: \x and. Format
      • 9 iterators and generators
      • *args and  **kwargs
      • 11 aspect-oriented programming AOP and adorners
      • 12 Duck type
      • python overloaded
      • 14 new and legacy classes
      • 15 __ Differences between new__ and init
      • 16 Singleton mode
        • 1 using __new__ methods
        • 2 shared properties
        • 3 Adorner version
        • 4 Import Method
      • in python scope
      • the Gil thread global lock
      • 19 coprocessor
      • 20 closure
      • Lamb da function
      • python functional Programming
      • all copies in Python
      • python garbage collection mechanism
        • 1 reference count
        • 2 mark-purge mechanism
        • 3 Generational technology
      • python list
      • read,readline python is
      • and ReadLines
      • the difference between Python2 and 3
      • Super Init
      • Range and xrange
  • Operating system
    • 1 Select,poll and Epoll
    • 2 Scheduling algorithm
    • 3 dead Lock
    • 4 program compilation and linking
      • 1 preprocessing
      • 2 compiling
      • 3 Assembly
      • 4 links
    • 5 static links and dynamic links
    • 6 Virtual Memory Technology
    • 7 Pagination and segmentation
      • The main difference between pagination and segmentation
    • 8 Page Replacement algorithm
    • 9 Edge triggering and horizontal triggering
  • Database
    • 1 Business
    • 2 Database Indexes
    • 3 Redis Principles
      • What is Redis?
      • Redis Database
      • Redis drawbacks
    • 4 optimistic lock and pessimistic lock
    • 5 MVCC
      • How MySQL's InnoDB engine is implemented MVCC
    • 6 MyISAM and InnoDB
  • Internet
    • 13-Time handshake
    • Wave 24 times
    • 3 ARP protocol
    • 4 the difference between Urllib and URLLIB2
    • 5 post and get
    • 6 Cookies and session
    • 7 The difference between Apache and Nginx
    • 8 Site User Password Save
    • 9 HTTP and HTTPS
    • Ten xsrf and XSS
    • 11 Idempotent idempotence
    • RESTful Architecture (SOAP,RPC)
    • SOAP
    • RPC
    • CGI and WSGI
    • 16 Man-in-the-middle attack
    • c10k questions
    • Socket
    • 19 Browser Cache
    • HTTP1.0 and HTTP1.1
    • Ajax
  • *nix
    • UNIX inter-Process communication mode (IPC)
  • Data
    • 1 red and black trees
  • Programming questions
    • 1 Stair problem/Fibonacci
    • 2 Abnormal stair problems
    • 3 Rectangle Overlay
    • 4 Young Matrix Search
    • 5 Removing duplicate elements from a list
    • 6 Linked list paired swap
    • 7 ways to create a dictionary
      • 1 Create directly
      • 2 Factory method
      • 3 Fromkeys () method
    • 8 Merging two ordered lists
    • 9 cross-linked list for intersection
    • 102 points Find
    • 11 Quick-Line
    • 12 Change Questions
    • 13 breadth traversal and deep traversal of binary trees
    • 17 Pre-and post-post traversal
    • 18 Seeking maximum tree depth
    • 19 Ask if the two trees are the same
    • 20 Preface order in sequence
    • 21 single-linked list reverse
    • Whether the 222 string is a modified word
    • 23 Dynamic planning Issues

One, Python language features

function parameter Passing in 1.python

function parameter simultaneous value or pass reference?

# Immutable Object A = 1def fun (a):    print ("func_in", ID (a))            # func_in 1868805184    a = 2    print ("Re-point", ID (a), ID (2)   # re-point 1868805216 1868805216print ("Func_out", ID (a), ID (1))        # func_out 1868805184 1868805184fun (a) print ( A)                               # # Immutable object passed in
# mutable Object A = []def fun (a):    print ("func_in", ID (a))  # func_in 36683976    a.append (1) print ("Func_out", ID (a))      # Func_out 36683976fun (a) print (a)                     # [1]# Variable object passed in

What is remembered here is that the type belongs to the object, not the variable. There are two types of objects, "mutable" and "non-changing" (immutable) objects. In Python, strings, tuples, and numbers are immutable objects, and list, Dict, set, and so on, are objects that can be modified. (This is the point of this question)

When a reference is passed to a function, the function automatically copies a reference, and the reference in the function does not have a semi-gross relationship with the outside reference. So in the first example, the function refers to an immutable object, and when the function returns, the outside reference does not feel half-hairy. And the second example is different, A reference in a function refers to a mutable object, and it is manipulated in memory as if it were positioned as a pointer address.

Meta-class in 2.python (Metaclass)

  a meta-class is a class of classes. Just as a class defines the behavior of an instance of a class, the meta-class defines the behavior of a class. a class is an instance of a meta-class.

  

  

in Python, you can use arbitrary callable elements for a meta class (such as Jerub Display), but the more useful approach is actually to make it an actual class itself. type is the usual meta-class in Python. If you want to know, yes, type It itself is a class, and it is its own type. you won't be able to type recreate something like Python , but Python will cheat. to create your own meta-class in Python, you really just want the subclass type .

meta-class is most commonly used as a class factory. just like creating an instance of a class by invoking a class, Python creates a new class by calling the meta-class (when it executes the ' class ' statement). in combination with conventions __init__ and __new__ methods, the meta-class allows you to do "extra things" when creating a class, such as registering a new class with some registry, Or even completely replace the class with something else.

when class when the statement is executed, Python first class Executes the body of the statement in the form of a normal block of code . The resulting namespace (a dictionary) holds the attributes to be categorized. A meta-class is a base class that is viewed by a class (a meta-class), to be the class __metaclass__ (if any) or a __metaclass__ global variable . property to determine the . the meta-class then invokes the class's name, base class, and attributes to instantiate it.

However, the meta-class actually defines the a class of the type , not just a factory, so you can do more things. For example, you can define a general method on a meta class. These meta-class methods are like class methods, because they can be called on a class without an instance, but they are also not like class methods because they cannot be called on an instance of a class. type.__subclasses__() is an type Example of a method of a meta- class . You can also define normal "magic" methods, such as __add__ , __iter__ and __getattr__ , to perform or change the behavior of a class.

Detailed Link: What is a meta-class?

[Email protected] (static method) and @classmethod (class method)

Class A (object):    # normal method    def foo (self,x):        print ("Executing foo (%s,%s)"% (self,x))    # classes Method    @ Classmethod    def class_foo (cls,x):        print ("Executing class_foo (%s,%s)"% (cls,x))    # static method    @ Staticmethod    def static_foo (x):        print ("Executing Static_foo (%s)"%x) A=a ()

For instance A, instance a has no method, it calls a method of Class A, and instance a only defines Def __init__ (self): After creating its own properties, you can see the properties you own through Dir (a), and not the self parameter for class methods. Instead of the CLS, which is the class itself, instance a cannot be called; for static methods, a static method is a tool function of Class A, which is equivalent to a normal external function that both Class A and instance a can invoke.

4. Class variables and instance variables

Class variables:

is a value that can be shared among all instances of a class (that is, they are not assigned individually to each instance). For example, in the following example, Num_of_instance is a class variable that tracks how many instances of test exist.

Instance variable:

Once instantiated, each instance has a separate variable.

Class Test (object):    num_of_instance = 0    def __init__ (self, name):        self.name = name        test.num_of_ Instance + = 1if __name__ = = ' __main__ ':    print (test.num_of_instance)         # 0    t1 = Test (' Jack ')    print ( test.num_of_instance)         # 1    t2 = Test (' Lucy ')    print (T1.name, t1.num_of_instance)  # jack 2    Print (T2.name, T2.num_of_instance)  # lucy 2

Here's an example:

Class Person:    name= "AAA" P1=person () P2=person () p1.name= "BBB" Print (p1.name)      # bbbprint (p2.name)      # Aaaprint (Person.name)  # AAA

Here p1.name="bbb" is the instance called the class variable, which is actually the same as above the first problem, is the function of the argument, the first p1.name is a pointer to the class variable, but in the scope of the name="aaa" instance of the class variable to change the reference, it becomes an instance variable, Self.name no longer references the class variable name of person.

One more example:

Class Person:    Name=[]p1=person () P2=person () p1.name.append (1) print (p1.name)      # [1]print (P2.name)      # [1] Print (Person.name)  # [1]

Why is this? Because only the assignment operation will give the instance a new property, it is now the append operation, and the operation is the name in the class = []

5.python Introspection

This is also Python's awesome character.

Introspection is a program written by an object-oriented language that can know the type of an object at run time. A simple sentence is the type of object that can be obtained at run time. For example type (), dir (), GetAttr (), hasattr (), Isinstance ().

  

Original link: Face question

Python face question

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.