A summary of Python basics, databases, networks, programming, etc.

Source: Internet
Author: User
Tags instance method
Python language Features 1 python's function parameter pass

See two examples:

A = 1
def fun (a):
    a = 2
fun (a)
print a  # 1
A = []
def Fun (a):
    a.append (1)
Fun (a)
print a  # [1]

All variables can be understood as "references" to an object in memory, or it can seem like a void* in C.

Using IDs to refer to the memory address of a can be more understandable:

A = 1
def fun (a):
    print "func_in", ID (a)   # func_in 41322472
    a = 2
    print "Re-point", ID (a), ID (2) c17/># re-point 41322448 41322448
print "Func_out" id (a), ID (1)  # func_out 41322472 41322472 Fun
(a)
print a  # 1

Note: Specific values may be different when running on different computers.

As you can see, after a = 2 is executed, the value that is saved in a reference, that is, the memory address changes, the address of the original 1 object becomes the memory address of the 2 entity object.

And the 2nd example a references saved memory values will not change:

A = []
def Fun (a):
    print "func_in", ID (a)  # func_in 53629256
    a.append (1)
print "Func_out", ID ( A)     # func_out 53629256
Fun (a)
print a  # [1]

The thing to remember here is that the type belongs to the object, not to the variable. There are two types of objects, "mutable" and "Immutable" (immutable) objects. In Python, strings, tuples, and numbers are objects that cannot be changed, while list, Dict, set, and so on, are objects that can be modified. (That's the point of this problem)

When a reference is passed to a function, the function automatically copies a reference, the reference in this function does not have a half wool 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 is not half hairy. And the second example is different, A reference within a function points to a mutable object, which is modified in memory just as the pointer address is positioned.

If it's not clear, here's a better explanation: Http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference 2 The Meta class in Python (Metaclass)

This is very infrequently used, but the complex structure like ORM is still needed, please see: Http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 3 @staticmethod and @classmethod

Python actually has 3 methods, static methods (Staticmethod), class methods (Classmethod), and instance methods, as follows:

def foo (x):
    print "executing foo (%s)"% (x)

class A (object):
    def foo (self,x):
        print "executing foo" (%s,% s) "% (self,x)

    @classmethod
    def class_foo (cls,x):
        print" executing class_foo (%s,%s) "% (cls,x)

    @ Staticmethod
    def static_foo (x):
        print "executing static_foo (%s)"%x

a=a ()

Here we first understand the self and the CLS within the function arguments. This self and the CLS are bindings to classes or instances, and for ordinary functions we can call Foo (x), which is the most commonly used, and its work has nothing to do with anything (class, instance). For instance methods, We know that every time we define a method in a class we need to bind this instance, that is, foo (self, x), why do you do it? Because the invocation of an instance method is inseparable from an instance, we need to pass the instance to the function itself, which is A.foo (x) (actually foo (a, x)). class method, except that it passes a class instead of an instance, A.class_foo (x). Note that the self and the CLS can replace other parameters here, but the Python convention is either, or don't change it.

For static methods, like normal methods, there is no need to bind to whom, and the only difference is that it needs to be invoked using either A.static_foo (x) or A.static_foo (x).

\ instance Method class Method static Method
A = A () A.foo (x) A.class_foo (x) A.static_foo (x)
A Not available A.class_foo (x) A.static_foo (x)

More on this issue: http://stackoverflow.com/questions/136097/ What-is-the-difference-between-staticmethod-and-classmethod-in-python 4 class variables and instance variables

Class variables:

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

Instance variables:

Once instantiated, each instance has a variable that is owned individually.

Class Test (object):  
    num_of_instance = 0  
    def __init__ (self, name):  
        self.name = name  
        test.num_of_ Instance + + 1  
  
if __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

Examples of supplements

Class Person:
    name= "AAA"

P1=person ()
P2=person ()
p1.name= "BBB"
print p1.name  # BBB
print P2.name  # AAA
Print person.name  # AAA

Here P1.name= "BBB" is the instance that invokes the class variable, this is actually the same as the first question, is the question of function argument, P1.name first point to the class variable Name= "AAA", but in the scope of the instance to change the reference to the class variable, it becomes an instance variable, Self.name no longer references the class variable name of person.

Take a look at the following example:

Class Person:
    name=[]

P1=person ()
P2=person ()
p1.name.append (1)
print P1.name  # [1]
print P2.name  # [1]
print Person.name  # [1]

Reference: Http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block 5 python introspection

This is also Python's awesome feature.

Introspection is the object-oriented language in which the program is written to know the type of object. The simple phrase is that the runtime is able to get the type of object. such as type (), dir (), GetAttr (), hasattr (), Isinstance ().

A = [1,2,3]
B = {' A ': 1, ' B ': 2, ' C ': 3}
c = True
print type (a), type (b), type (c) # <type ' list ' > <type ' dic T ' > <type ' bool ' >
print isinstance (a,list)  # True
6 Dictionary derivation

You may have seen the derivation of the list, but have not seen the dictionary derivation, in 2.7 to join:

D = {Key:value for (key, value) in Iterable}
7 single underline and double underline in Python
 >>> class MyClass (): ... def __init__ (self): ... self.__superprivate = "Hello" ... Self._semiprivate = ", world!" ... >>> mc = MyClass () >>> print mc.__superprivate traceback (Most rec ENT call last): File "<stdin>", line 1, in <module> Attributeerror:myclass instance has no attribut 

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.