TECH_PYTHON

极大提高你的Python编程能力——明白python的执行模式

2017-09-22  本文已影响9人  抬头挺胸才算活着

本片笔记学习自:Drastically Improve Your Python: Understanding Python's Execution Model

有时我们期待python会发生A情况,但是却发生了B,根本原因就是因为你没有完全懂Python。本片文章将带你理解python的变量,对象,函数背后的东西。

一切都是对象?

这句话可能会让你想到:1.可能python像java一样,用户写的所有东西都放在一个对象中。2.所有的python里面的东西都被当作一个个的对象。
第一个想法是错误的
第二个想法是对的,数值、类、函数、对象都是对象,这让这些都有一些对象的特性,类型有方法、函数有属性、模块可以被当作参数等等。
经常困惑读者的一个python特性是:当我们用print打印出我们自定义的对象时老是打印出一些奇奇怪怪的东西出来,但是我们打印strings或者ints这些内建的类型时却正常地打印出他们的值。例如下面的代码及其运行结果。

class Foo(): pass
foo = Foo()
print(foo)

打印结果:

<__main__.Foo object at 0x0000000002B307F0>

这里首先要明白foo作为一个变量,并没有存储Foo实例的值,只是绑定了一个Foo实例,打印的结果就是Foo实例的地址。这里的变量跟C语言等的变量并不一样,C语言的变量就是指向一块固定地址的内容,而python的变量跟C语言的指针更像,可以时刻改变指针的指向而绑定不同的内存单元。

What's in a name...
names in Python are not unlike names in the real world. If my wife calls me "Jeff", my dad calls me "Jeffrey", and my boss calls me "Idiot", it doesn't fundamentally change me. If my boss decides to call me "Captain Programming," great, but it still hasn't changed anything about me. It does mean, however, that if my wife kills "Jeff" (and who could blame her), "Captain Programming" is also dead. Likewise, in Python binding a name to an object doesn't change it. Changing some property of the object, however, will be reflected in all other names bound to that object.

所有能写在等式右边都是对象,不相信我?如果10只是一个数字,恐怕不会有add属性

foo = 10
>>> print(foo.__add__)
<method-wrapper '__add__' of int object at 0x8502c0>

我们可以用dir(10)进一步查看10所含有的所有属性

['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

>>> a = 'foo'
>>> a
'foo'
>>> b = a
>>> a += 'bar'
>>> a
'foobar'
>>> b
'foo'

你可能会听到说修改字符串好慢!是的,你需要首先分配一个新的字符串的空间然后将内容复制过去。因此改变不可变对象代价是比较高的。

下面的例子说明了元组的不变只是绑定的关系不变,绑定的对象可以改变。

>>> class Foo():
...     def __init__(self):
...             self.value = 0
...     def __str__(self):
...             return str(self.value)
...     def __repr__(self):
...             return str(self.value)
... 
>>> f = Foo()
>>> print(f)
0
>>> foo_tuple = (f, f)
>>> print(foo_tuple)
(0, 0)
>>> foo_tuple[0] = 100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> f.value = 999
>>> print(f)
999
>>> print(foo_tuple)
(999, 999)
GLOBAL_CONSTANT = 42

def print_some_weird_calculation(value):
    number_of_digits = len(str(value))

    def print_formatted_calculation(result):
        print('{value} * {constant} = {result}'.format(value=value,
            constant=GLOBAL_CONSTANT, result=result))
        print('{}   {}'.format('^' * number_of_digits, '++'))
        print('\nKey: ^ points to your number, + points to constant')

    print_formatted_calculation(value * GLOBAL_CONSTANT)

>>> print_some_weird_calculation(123)
123 * 42 = 5166
^^^   ++

Key: ^ points to your number, + points to constant

python是怎么实现我们在内层作用域中可以使用外层作用域的值?引用值的时候,首先从最里面的作用域的变量中查找,如果没有就向外面的作用域进行查找,一层层找下去。

上一篇下一篇

猜你喜欢

热点阅读