Python

本文概述了Python编程中的核心概念,包括语法糖、GUI设计、编辑器使用、基本概念如docstring、重载规则、内省、可变参数等,以及Pythonic实践如迭代多列表、使用zip函数等。此外,还涉及了面向对象编程、函数参数传递、内存管理、数据结构和算法等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

### 语法糖

1. 如何方便地打印 class 的 instance 的 所有 data attribute

Print all properties of a Python Class

an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print ', '.join("%s: %s" % item for item in attrs.items())

### 方案比较

1. GUI
https://groups.google.com/forum/#!searchin/pongba/设计GUI/pongba/e53UZFAWwb4/kKbxzsmGrCwJ

pyQT for 2.7 在windows 上安装使用十分便捷。


### 编辑器

关于 Blank Line

emacs 中,C-M-\ :不能 缩进 空行,然而,Python major mode 的 “缩进依据”是 “前一行”的缩进。由于Blank Line 不会被Indent,因此,空行之后的行只能被 Indent 。


### 基本概念

1. doc string


### Feature

1. 重载规则

不区分arg name 或者 type,python 只认 method name。 这也就意味着:从 C++ 的理解,所有的 method 都是 virtual 的:只要同名(不管参数列表),就覆盖。

注意: C++ 中,不同class的method,即使 explicit 定义的 args 是相同的,也并不意味着函数是同一个:因为,this 指针 的 类型不同 !

但是,virtual 的话,统一都是 base 的指针,因此,实际上每个 method 的 C 形式 的 prototype 是 相同的。

why :

Guido, the original author of Python, explains method overriding this way: "Derived classes may override methods
of their base classes. Because methods have no special privileges when calling other methods of the same object, a
method of a base class that calls another method defined in the same base class, may in fact end up calling a method
of a derived class that overrides it. 


2. 内省

所谓内省,实际上主要是指在runtime获得一个对象的全部类型信息。这样可以提供更好的编程灵活性。
Java中的introspection是通过ReflectionAPI来做到的。Python中的内省主要是通过一下几个方法:
[1] type/str/dir :dir : 得到所有的 attribute
[2] getattr


3.可变参数

*args表示任何多个无名参数,它是一个tuple;

**kwargs表示关键字参数,它是一个dict。

并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前,像foo(a=1, b='2', c=3, a', 1, None, )这样调用的话,会提示语法错误“SyntaxError: non-keyword arg after keyword arg”。

例子:

foo('a', 1, None, a=1, b='2', c=3) :
args =  ('a', 1, None) 
kwargs =  {'a': 1, 'c': 3, 'b': '2'} 


### 原理

1. Data Model ( 参看 Language Reference )

所有的东西都是 object 或者 object 之间的 relation。 三个属性 : identity, type 和 value 。 其中,identity 相当于 memory address。 identity 和 type 是伴随object 一生的,而value 是“不定”的。

【Q】此处何谓 relation? 一种解释是 reference 。 


谈到 mutable , 其实讲的是 mutability 。

对于 简单的 objects 来讲,mutability 讲的就是 object 的 value 的可变性。value可以改变就是 mutable 。  而 immutable 的 objects ,一旦 create ,value 就不会改变。

但是,对于 container,value 指的的是 container 中 objects 的 value , 而 mutability,指的是 container 中 objects 的 identities。


所谓的 immutable container 指的是 container 中, objects 的 identity 是不变的。


是否是immutable,对于 objects 的 behavior(尤其是 create)是有影响的。

1)  对于 immutable : (numbers, booleans, strings, tuples, frozensets) ,比如下面例子中的 integer type “1” 

a=b=1 , 

a和b 这两个 reference 被绑定到同一个 integer objects ( 1 嘛 ),并不产生新的objects。


2) 对于 mutable,显然,a 和 b 应该独立引用不同的object。

  a=[] , b=[] 实际上创建了两个 [ ] objects。


但是,注意:a = b = [] 的 语义:两个ref 引用同一个 [ ] objects。


2. GC 和 del

resource 直到 objects 被 garbage collected 才会被 free,但是,GC 不保证何时 回收。

Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.
Deletion of a target list recursively deletes each target, from left to right.
Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.
It is illegal to delete a name from the local namespace if it occurs as a free variable in a nested block.
Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).

只有当 离开 name scope 的时候,reference 指向的 object 才会被 gc。

摘自 《dive》:

The technical term for this form of garbage collection is "reference counting". Python keeps a list of references to
every instance created. In the above example, there was only one reference to the FileInfo instance: the local
variable f. When the function ends, the variable f goes out of scope, so the reference count drops to 0, and Python
destroys the instance automatically.  采用“引用计数”。当引用为0,自动销毁。

If you created two instances that referenced each other (for instance, a doubly−linked list, where each node
has a pointer to the previous and next node in the list), neither instance would ever be destroyed automatically because
Python (correctly) believed that there is always a reference to each instance. Python 2.0 has an additional form of
garbage collection called "mark−and−sweep" which is smart enough to notice this virtual gridlock and clean up
circular references correctly. 

python 2.0 之后 采用了 mark and sweep,解决了 circular references  的问题。


2. None(native type),id(),type(),is ,== 和 !=

None :这种类型是 single value & single object ,通过 None Keyword 来 access。

    is    :比较 id(identity ),即 id(a) == id(b) 

== 和 != :比较 Value

重载: You can override an object's__eq__ and __ne__ methods to determine what that means.

但,还是有坑:

【不精确的解释】method object 是动态创建和销毁的,因此,同一类型不同 instance 的 method 是不同的。

http://stackoverflow.com/questions/2906177/what-is-the-difference-between-a-is-b-and-ida-idb-in-python


2. 函数参数传递

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:


参数传递都是传值,但是,这个值是 reference --> 等价为 “传引用”
修改reference 即修改原对象。


但是,如果在函数中 使用了 = ,就相当于对 ref 进行重新 rebind ,不会返回 local 的值。
解决: return 是最简单的方法。
ref: 
1.解释: http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference
2.官方和例子:http://www.tutorialspoint.com/python/python_functions.htm

3. 面向对象

super(ChildB, self).method() :类型ChildB 的 instance 调用类型 B 的 基类的method()。 

好处:相比较于 Base.__init__(self) , 需要引用 Base 的 名字。【模糊的解释】对于 多重继承来讲,有好处。见ref 中,提到的 fun thing。

ref:

http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods


### Pythonic

2. how can I iterate through two lists in parallel in Python?
for f, b in zip(foo, bar):
    print(f, b)

3. zip
为什么用zip?因为 zip 返回的是 shortest one的 长度。
这样,注释掉一部分 test case 时,不需要去注释相依的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值