Python interview_python
https://github.com/taizilongxu/interview_python
1 Python的函数参数传递
strings, tuples, 和numbers是不可更改的对象,而list,dict等则是可以修改的对象
2 Python中的元类(metaclass)
3 @staticmethod和@classmethod
python 三个方法,静态方法(staticmethod),类方法(classmethod),实例方法
4 类变量和实例变量
类变量就是供类使用的变量,实例变量就是供实例使用的.
若是list,dict修改实例变量,类变量也改变。strings, tuples, 和numbers是不可更改的对象,故实例变量和类变量不同。
5 Python自省
自省就是面向对象的语言所写的程序在运行时,所能知道对象的类型.简单一句就是运行时能够获得对象的类型.比如type(),dir(),getattr(),hasattr(),isinstance().
6 字典推导式
列表推导式(list comprehension)
In [39]: [x*x for x in range(10)]
Out[39]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2.7加入字典推导式
>>> strings = ['import','is','with','if','file','exception']
>>> D = {key: val for val,key in enumerate(strings)}
>>> D
{'exception': 5, 'is': 1, 'file': 4, 'import': 0, 'with': 2, 'if': 3}
7 单下划线、双下划线
single underscore : private
>>> class MyClass():
... def __init__(self):
... self.__superprivate = "Hello"
... self._semiprivate = ", world!"
...
>>> mc = MyClass()
>>> print mc.__superprivate
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: myClass instance has no attribute '__superprivate'
>>> print mc._semiprivate
, world!
>>> print mc.__dict__
{'_MyClass__superprivate': 'Hello', '_semiprivate': ', world!'}
8 字符串格式化:%和.format
sub1 = "python string!"
sub2 = "an arg" a = "i am a %s" % sub1
b = "i am a {0}".format(sub1) c = "with %(kwarg)s!" % {'kwarg':sub2}
d = "with {kwarg}!".format(kwarg=sub2) print a # "i am a python string!"
print b # "i am a python string!"
print c # "with an arg!"
print d # "with an arg!" "hi there %s" % (name,) # supply the single argument as a single-item tuple
9 迭代器和生成器
10 *args and **kwargs
*args,例如,它可以传递任意数量的参数. You would use *args when you're not sure how many arguments might be passed to your function
**kwargs,允许你使用没有事先定义的参数名.
*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个dict。
https://stackoverflow.com/questions/3394835/args-and-kwargs/3394898#3394898
def foo(*args, **kwargs):
print 'args = ', args
print 'kwargs = ', kwargs
print '---------------------------------------' if __name__ == '__main__':
foo(1,2,3,4)
foo(a=1,b=2,c=3)
foo(1,2,3,4, a=1,b=2,c=3)
foo('a', 1, None, a=1, b='2', c=3)
输出结果如下:
args = (1, 2, 3, 4)
kwargs = {}
---------------------------------------
args = ()
kwargs = {'a': 1, 'c': 3, 'b': 2}
---------------------------------------
args = (1, 2, 3, 4)
kwargs = {'a': 1, 'c': 3, 'b': 2}
---------------------------------------
args = ('a', 1, None)
kwargs = {'a': 1, 'c': 3, 'b': '2'}
---------------------------------------
# 当调用函数时你也可以用 * 和 ** 语法
def star_operation(name, value, count):
print("Name: {}, Value: {}, Count: {}".format(name, value, count)) if __name__ == "__main__": # 它可以传递列表(或者元组)的每一项并把它们解包. 注意必须与它们在函数里的参数相吻合
a_list = ["名字", "值", "计数器"]
a_dict = {'a':1, 'b':2, 'b':3}
star_operation(*a_list)
star_operation(**a_dict.items())
输出:
Name: 名字, Value: 值, Count: 计数器
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-33-d38ee010e1b9> in <module>()
10 a_dict = {'a':1, 'b':2, 'b':3}
11 star_operation(*a_list)
---> 12 star_operation(**a_dict.items()) TypeError: star_operation() argument after ** must be a mapping, not list
**后面必须是 mapping,映射
11 面向切面编程AOP和装饰器
装饰器的作用就是为已经存在的对象添加额外的功能
# how decorators work def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped @makebold
@makeitalic
def hello():
return "hello world" print hello() ## returns "<b><i>hello world</i></b>"
函数即是对象
def shout(word="yes")
return word.capitalize()+"!" print (shout()) # Yes! # As an object, you can assign the function to a variable like any other object
scream = shout # Notice we don't use parenthese: we are not calling the fuction,
# we are putting the function "shout" into the variable "scream".
# It means you can then call "shout" from "scream":
print (scream()) # Yes! # More than that, it means you can remove the old name 'shout',
# and the function will still be accessible from 'scream' del shout
try:
print(shout())
except NameError, e:
print(e) # "name 'shout' is not defined" print(scream()) # Yes!
python: function can be defined inside another function / 函数能够定义在其他函数内。
Functions references:
1.can be assigned to a varible
2.can be defined in another function
def getTalk(kind="shout"):
# We define functions on the fly
def shout(word="yes"):
return word.capitalize()+"!"
def whisper(word="yes") :
return word.lower()+"...";
# Then we return one of them
if kind == "shout":
# We don't use "()", we are not calling the function, we are returning the function object
return shout
else:
return whisper
# How do you use this strange beast?
# Get the function and assign it to a variable
talk = getTalk()
# You can see that "talk" is here a function object:
print(talk)
#outputs : <function shout at 0xb7ea817c>
# The object is the one returned by the function:
print(talk())
#outputs : Yes!
# And you can even use it directly if you feel wild:
print(getTalk("whisper")())
#outputs : yes...
Decorator :
'wrappers', let you execute code before and after the function they decorate without modifying the function itself.
methods and functions are really the same. The only difference is that methods expect that their first argument is a reference to the current object (self).
方法和函数的唯一区别是,方法的第一个参数是对当前对象的引用,self.
Python自带的几个装饰器:property,staticmethod。。
Django 使用装饰器来管理缓存和权限控制。
Twisted 用来实现异步调用。
12 鸭子类型
鸭子类型是动态类型的一种风格,在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由当前 方法和属性的集合所决定。
例如,在不使用鸭子类型的语言中,我们可以编写一个函数,它接受一个类型为鸭的对象,并调用它的走和叫方法。在使用鸭子类型的语言中,这样的一个函数可以接受一个任意类型的对象,并调用它的走和叫方法。如果这些需要被调用的方法不存在,那么将引发一个运行时错误。任何拥有这样的正确的走和叫方法的对象都可被函数接受的这种行为引出了以上表述,这种决定类型的方式因此得名。
网络
5 Post和Get
区别:
一个用于获取数据,一个用于修改数据。
Python interview_python的更多相关文章
- Python题目
https://github.com/taizilongxu/interview_python 1 Python的函数参数传递 strings, tuples, 和numbers是不可更改的对象,而l ...
- Python资源大全
The Python Tutorial (Python 2.7.11) 的中文翻译版本.Python Tutorial 为初学 Python 必备官方教程,本教程适用于 Python 2.7.X 系列 ...
- 转--Python语言特性
1 Python的函数参数传递 看两个例子: a = 1 def fun(a): a = 2 fun(a) print a # 1 a = [] def fun(a): a.append(1) fun ...
- python(十四)新式类和旧式类
这里有个重要概念呢在下面那个链接 http://blog.csdn.net/zimou5581/article/details/53053775 http://www.cnblogs.com/btch ...
- 面试总结之PYTHON
source code https://github.com/haoran119/interview/tree/master/interview%20summary%20of%20python [ZZ ...
- Python 学习笔记---基础篇
1. 简单测试局域网中的电脑是否连通.这些电脑的ip范围从192.168.0.101到192.168.0.200 import subprocess cmd="cmd.exe" b ...
- Python面试题目--汇总
原文链接-https://github.com/taizilongxu/interview_python Python语言特性 1 Python的函数参数传递 2 Python中的元类(metacla ...
- Python基础知识小结
1. 关于函数传参 def func(n, *args, **kwargs): print n print args print kwargs if __name__ == '__main__': # ...
- python知识点, float不能用 != 判断
python知识点链接:https://github.com/taizilongxu/interview_python 搜索:python最佳事件 书单:http://lucida.me/blog/d ...
随机推荐
- Irrlicht 3D Engine 笔记系列之 教程4 - Movement
作者: i_dovelemon 日期: 2014 / 12 / 16 来源: CSDN 主题: Event Receiver, Animator, Framerate independent move ...
- C++学习总结1
一.内存管理 一般new 与 delete 同时出现.假如释放一个对象用 delete p即可.多个对象用delet [ ]p 即:new与delete需要搭配好. C++继承了C的许多函数,mal ...
- vs项目添加链接文件
在vs2012(或以后版本)中,从一个项目中拖拽文件到另一项目,并按住alt键,会生成链接文件. 项目文件中会生成link节点. <ItemGroup> <Compile Inclu ...
- 如何把网页或html内容生成图片
网页或html内容生成图片 今天想把做好的html内容或网页生成一张图片,没有网页在线版的生成或转换工具,除非下载客户端软件使用. 不过,发现可以利用搜狗高速浏览器和360浏览器生成图片,这里讲解 ...
- 服务器文档下载zip格式 SQL Server SQL分页查询 C#过滤html标签 EF 延时加载与死锁 在JS方法中返回多个值的三种方法(转载) IEnumerable,ICollection,IList接口问题 不吹不擂,你想要的Python面试都在这里了【315+道题】 基于mvc三层架构和ajax技术实现最简单的文件上传 事件管理
服务器文档下载zip格式 刚好这次项目中遇到了这个东西,就来弄一下,挺简单的,但是前台调用的时候弄错了,浪费了大半天的时间,本人也是菜鸟一枚.开始吧.(MVC的) @using Rattan.Co ...
- Springmvc返回信息乱码解决
恩...基本上所有的配置信息都弄上了,但是还是乱码,最后在方法上面添加了下面的参数,就完美解决了: @RequestMapping(value="/action.action",m ...
- nice命令兼容性分析实例
背景 产品实验室出现一例日志转储问题,经定位发现当前版本号没有提供nice命令,而cron拉起定时任务时,却调用了nice命令,对定时任务做优先级调整. 毫无疑问兴许版本号须要提供nice命令,可是是 ...
- C递归算法与栈的分析,非全然二叉树遍历分析---ShinePans
对于递归,这里面的分析最好当然是用图形的方式来分析了.这里来总结一下 1.首先对于栈的理解: 先进后出,后进先出 先进后出 2.在进行非全然二叉树的存储之后,我们要做的是对其 ...
- npm 淘宝设置代理
直接安装cnpm导致无限索引,因此直接使用代理 方法一: 直接在当前用户文件夹下,npmrc 文件上直接设置代理:registry=https://registry.npm.taobao.org 方法 ...
- Java类加载器( 死磕8)
[正文]Java类加载器( CLassLoader ) 死磕 8: 使用ASM,和类加载器实现AOP 本小节目录 8.1. ASM字节码操作框架简介 8.2. ASM和访问者模式 8.3. 用于增 ...