第一节,模块、类对象与functools
一、模块
1、依赖路径:程序导入模块的搜索路径包括它的内置模块和sys.path路径列表,包括:
①程序所在目录 ②环境变量PYTHONPATH所设置的路径 ③标准库路径
导入过程:模块第一次导入时编译成.pyc字节码,再次导入时检查.pyc和.py文件的mtime来决定是否重新编译。
模块属性:dir(mod),查看模块mod.py的内置属性和函数。
eg:a.py和b.py在同一目录src下, # a.py x="var x in module b" def funA(x) : print(x) # test.py: import a # 若想直接使用funA, 则from myilb import funA import sys print(a.x) a.funA()
使用imp库重新导入模块:
二、类对象
class Animal: def speak(self): print("this is :%s\nits sound is :%s!" % (self, self.sound())) def sound(self): raise NotImplementedError("you must override this method")
import animal class Cow(animal.Animal): # 定义Cow类,继承自Animal name = "class cow" # 全局类属性 def __init__(self): self.name = "object cow" self.age = 12 self.course = ["cs computer", "math anaylise", "operate system"] self.index = -1 def sound(self): return "shine " + Cow.name def __str__(self): return f'{self.__class__}, name is {self.name}, age is {self.age}.' def __del__(self): del self.name, self.age def __call__(self, mode=0): print('your selected is :', mode) def __len__(self): return len(self.course) """ def __getitem__(self, item): return self.course[item] """ def __iter__(self): return self def __next__(self): self.index += 1 if self.index > len(self.course) - 1: raise StopIteration() return "your course is :" + self.course[self.index]
# main.py
import cow cowa = cow.Cow() cowa.speak() cowa.country = "China" # setattr hasattr getattr setattr(cowa, "store", {'xu': "shine", 2: "163.com"}) print(hasattr(cowa, "speak"), hasattr(cowa, "age"), cowa.name, cowa.country, getattr(cowa, "store")) cowa(2) # 相当于cowa.__call__(2) 重载了()运算符 for x in cowa: print(x) def decorate(fn): print('decorate start...') fn() print('decorate end.') return 'decorate return.' @decorate def fun(): print('the decorated function.') print(fun)
1、继承与多态
class Cow(animal.Animal) --- Cow 继承Animal。
对于__init__构造方法,如果子类中没有则调用父类的。
对于cowa.speak() 先在Cow后在Animal类中寻找speak()函数;调用过程中self始终是cowa,所以调用的self.sound不会报错!
知识点:子类继承的名称空间
一般嵌套函数可向外层搜索全局变量,而类/对象变量:分别有子类向父类深入搜索。
2、类特殊成员
① __new__(cls,[...)
__new__ 是真正的类构造方法,用于产生实例化对象(空属性)。它只取下 cls 参数,并把其他参数传给 __init__ 绘制对象初始化过程。
② __str__和__repr__
使用__str__之前:print(cowa) # <__main__.Cow object at 0x0000016ED4BABA90>
使用__str__函数自定义类输出值
③ __iter__、__next__和__getitem__
def __getitem__(self, item):
return self.course[item]
使对象可迭代,像元组列表一样。要么使用 __iter__、__next__,要么使用__getitem__ 这个使对象可以按下标访问
for x in object:
print(x)
④属性的hasattr、getattr、setattr
hasattr返回True False,getattr和setattr可以用.作用符代替。
⑤__call__重载()运算符,至少要有一个参数
obj(arg)相当于obj.__call__(arg)
⑥类方法和类静态方法
分别用@classmethod和@staticmethod修饰;类方法只能访问类成员 不能访问对象成员;类静态方法连类成员都不能访问,只是代码与类有关才放在类作用域中。
访问方式都是class.method()
⑦装饰函数@
示例所示的fun相当于decorate(fn)。 于是fun()相当于decorate(fn)(),但这里decorate返回的不是可调用函数。看这个例子
def decorate(func):
... def wrapper(*args, **kwargs):
... result = func(*args, **kwargs) return result.upper()
... return wrapper @decorate def fun(x: str): return x res = fun("abcd") print(res)
fun("abcd")相当于decorate(fun)("abcd"), 于是先执行decorate(fun) 再执行wrapper("abcd")。
wrapper的参数(*args, **kwargs)使fun的任意参数都被能传入。
总结:装饰器decorate中一定会执行fun, 装饰的是fun的上下文环境。
四、functools模块的工具partial()
使得inttwo = int(str,base=2)

2022-01-27 15:07:53

浙公网安备 33010602011771号