可变对象和不可变对象
https://zhuanlan.zhihu.com/p/34395671
dict与dir()区别
https://blog.csdn.net/lis_12/article/details/53521554
- if seq原理
print(8/2) # 4.0
ls.append
和ls.extend
区别- 闭包和装饰器
https://segmentfault.com/a/1190000004461404
- Nonlocal和global:nonlocal查找本地变量和全局变量之间的变量,其会优先寻找层级关系与闭包作用域最近的外部变量
- (注:在python函数中可以直接引用外部变量,但不能改写外部变量,只能使用global,nonlocal)
- Python代码规范遵循PEP8,检查代码是否规范可用的工具有:pylint,Flake8,Autopep8,Coverage,Yapf,cProfile
- all方法:
init中是否有all方法:
- 如果导入的模块中定义了all属性的话,那么只有在all内指定的属性、方法或者类才可以被导入,如果没有定义的话,只会导入所有的公有属性、方法和类。
```python from .init import func all=[‘func’]from common.init import func
test.py再导包
from common import func from common.init import func # 两种兼容
- 类中的属性或者方法如果本身是有下划线前缀的话,例如“_name”,直接from module import *的话是不会被导入的,但是如果在"__all__"中写明的话,是会被导入的。
```python
__all__ = [
"_func",
"_module",
]
class _module():
def _func1():
print("func1")
def _func():
print("func")
# test_property.py
from module import *
_func()
m = _module()
总结:
from <module> import *
默认行为会从给定空间导出所有符号(下划线开头的除外)__all__
只会影响from <module> import *
这种导入方式,
而from <module> import <member>
的导入方式并不受影响
__all__
可以用于隐藏属性,也可以让下划线开头的方法、类、变量显示
练习:
__all__ = ['A']
class A:
def __init__(self):
self.name = "a"
class B:
def __init__(self):
self.name = "b"
# 代码段1
from test import A,B
a = A()
print(a.name) # a
b = B()
print(b.name) # b
# 代码段2
from test import *
a = A()
print(a.name) # a
b = B()
print(b.name) # name 'B' is not defined
@setter 和@property
@property
定义只读属性,@setter
定义可读可写属性,@deleter
定义可读可写可删除属性
- 异常捕获
try…except…finally
- 二次探测再散列
https://www.jianshu.com/p/98466542ef5b?utm_campaign=maleskine
- 前置双下划线:__var
- 双下划线前缀会让Python解释器重写属性名称,以避免子类中的命名冲突。这也称为名称改写(name mangling),即解释器会更改变量的名称,以便在稍后扩展这个类时避免命名冲突。
```python
class Test:
def init(self):
self.foo = 11
self._bar = 23
self.__baz = 23 # '_Test__baz' 名字被换了
t=Test() dir(t) [‘Testbaz’, ‘class‘, ‘delattr‘, ‘dict‘, ‘dir‘, ‘doc‘, ‘eq‘, ‘format‘, ‘ge‘, ‘getattribute‘, ‘gt‘, ‘hash‘, ‘init‘, ‘le‘, ‘lt‘, ‘module‘, ‘ne‘, ‘new‘, ‘reduce‘, ‘reduceex‘, ‘repr‘, ‘setattr‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘, ‘weakref‘, ‘_bar’, ‘foo’] print(Test._Test__baz) # 23
<a name="g93QH"></a>
# pytest框架
[https://blog.csdn.net/lovedingd/article/details/98952868](https://blog.csdn.net/lovedingd/article/details/98952868)
```python
import pytest
def add(a, b):
"""
:param a:
:param b:
:return:
Error:
TypeError:if a is not a integer
"""
if not isinstance(a, int):
raise TypeError("a is not int!")
return a+b
def test_add():
assert add(1,2)==3
def test_add2():
with pytest.raises(TypeError):
add('1','2')
python的无重载机制
python没有重载机制。因为重载主要解决的问题的就是除了参数类型和参数个数不同之外,功能完全相同。