Python的一些基础知识
2017-05-13 11:43
337 查看
Python的语言特性
Python的函数参数传递
a = 1 def fun(a): a = 2 fun(a) print a #1 a = [] def fun(a): a.append(1) fun(a) print a #2
输出结果
1 [1]
所有的变量都可以理解是内存中一个对象的“引用”。
通过id来看引用a的内存地址可以比较理解:
a = 1 def fun(a): print "func_in", id(a) a = 2 print "re-point", id(a), id(2) print "func_out", id(a), id(1) fun(a) print a
输出结果为
func_out 12325208 12325208 func_in 12325208 re-point 12325184 12325184 1
在执行a=2之后,a引用中保存的值,即内存地址发生变化,由原来1对象的所在的地址变成了2这个实例对象的内存地址。
类型是属于对象的,而不是变量。
对象有两种:可更改(mutable)与不可更改(immutable)对象。在Python中,string, tuples, numbers是不可更改的对象,而list, dict等则是可以修改的对象。
Python中的元类(metaclass)
@staticmethod和@classmethod
Python有3个方法,即静态方法(staticmethod),类方法(classmethod)和实例方法。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() a.foo(1) a.class_foo(2) a.static_foo(3)
self cls是对类或者实例的绑定。
类变量和实例变量
class Person: name="aaa" p1=Person() p2=Person() p1.name="bbb" print p1.name # bbb print p2.name # aaa print Person.name # aaa
类变量就是提供类使用的变量,实例变量就是提供实例使用的变量。
字典推导式
d = {key: value for (key, value) in iterable }
Python中单下划线和双下划线
foo 一种约定,Python内部的名字,用来去吧区别其他用户自定义的命名,防止冲突;_foo 一种约定,用来指定变量私有,程序员可以用来指定私有变量
__foo 这个有真正的意义:解析器用_classname__foo来代替这个名字,以区别和其他类相同的命名.
字符串格式化 %和.format
迭代器和生成器
What does the “yield” keyword do in Python?*args and **kwargs
当不确定函数里将要传递多少参数时可以使用*args>>> def print_everything(*args): ... for count, thing in enumerate(args): ... print '{0}. {1}'.format(count, thing) ... >>> print_everything('apple', 'banana', 'cabbage') 0. apple 1. banana 2. cabbage
**kwargs允许使用没有事先定义的参数名。
>>> print_everything('apple', 'banana', 'cabbage') 0. apple 1. banana 2. cabbage >>> def table_things(**kwargs): ... for name, value in kwargs.items(): ... print '{0} = {1}'.format(name, value) ... >>> table_things(apple='fruit', change='vegetable') apple = fruit change = vegetable
*arfs **kwargs 可以同时在函数的定义中,但*args 必须在**kwargs前面
面向切面编程AOP和装饰器
面向切面编程AOP
装饰器
装饰器的作用是为已经存在的对象添加额外的功能。关于对装饰器的理解
Python重载
函数重载主要解决两个问题:1. 可变参数类型
2. 可变参数个数
new和init的区别
new是一个静态方法,而init是一个实例方法new方法会返回一个创建的实例,而init什么都不返回
只有在new返回一个cls的实例时后面的init才能被调用
当创建一个新实例时低啊用new,初始化一个实例时用init
相关文章推荐
- 一些python基础知识
- python基础学习中发现的一些小知识
- Python学习第三章《字符串》(成为高手前必须知道的一些基础知识)
- Python异常处理方面的一些基础知识。
- 学学python(1)一些基础知识点
- python爬虫项目前的一些基础知识(一)
- python初入门:与其他语言略有区别的一些基础知识1
- Python的一些基础知识
- Python3.x的一些基础知识(一)
- 一些关于Python的基础知识 - 千月的python linux 系统管理指南学习笔记(3)
- python的一些基础知识
- Python一些基础知识
- Python的一些基础知识
- 初学python的一些基础知识
- PythonTutorial-01 一些基础知识
- Python基础1:一些小知识汇总
- python的一些基础知识
- python的一些基础的知识
- Python中关于字符串对象的一些基础知识
- python的一些基础知识