惟一标识问题
面向对象python2-3的区别
importlib反射代码讲解
惟一标识问题
minion 配置的Id 就是惟一标志python
salt 'linux01' grains.item serialnumberlinux
salt 'linux01' grains.get serialnumber算法
面向对象python2-3的区别
python2app
经典类:深度优先this
demo.pyurl
代码spa
#!/usr/bin/env python \# _\*_ coding:utf-8 _\*_ class D(): # pass def run(self): print('this D') class C(D): # pass def run(self): print('this C') class B(D): pass # def run(self): # print('this B') class A(B,C): pass demo=A() \# print(A.mro()) demo.run()
用python2 运行.net
显示 this Dcode
新式类:C3算法(非广度优先)对象
代码
#!/usr/bin/env python \# _\*_ coding:utf-8 _\*_ class D(object): # pass def run(self): print('this D') class C(D): # pass def run(self): print('this C') class B(D): pass # def run(self): # print('this B') class A(B,C): pass demo=A() \# print(A.mro()) demo.run()
运行
显示this C
经典类类型
demo_class.py
代码
#!/usr/bin/env python \# _\*_ coding:utf-8 _\*_ class A(object): pass class B(): pass a=A() b=B() if type(a) == type(b): print('他们是同样的') print(type(a)) else: print('他们不是同样的') print(type(a)) print(type(b))
用python2 执行
显示 他们是不同的
{class '__main__.A'}
{type ''instance}
类型不一样
用python3 执行
显示 他们是不同的
{class '__main__A'}
{class ‘__main__B’}
类型相同,但不是同一个类
python3只有新式类
养成写入object的习惯
importlib反射代码讲解
反射:
getattr,hasattr,setattr
demo01.py
代码
#!/usr/bin/env python \# _\*_ coding:utf-8 _\*_ import importlib import os,sys \# sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(\_\_file\_\_)))) \# BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(\_\_file\_\_))) \# sys.path.append(BASEDIR) Host\_func\_dic = { 'disk':'func_demo.hosts.disk.Disk', } path=Host\_func\_dic.get('disk') module\_path,class\_name = path.rsplit('.',maxsplit=1) 从右开始,以.分割,只分割一次 print(module_path) print('----------') module = importlib.import\_module(module\_path) # from func_demo.hosts import disk # disk_class=getattr(disk,'Disk') disk\_class=getattr(module,class\_name) JG=disk_class() JG.run()
demo01.py
代码
#!/usr/bin/env python \# _\*_ coding:utf-8 _\*_ import importlib import os,sys \# sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(\_\_file\_\_)))) \# BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(\_\_file\_\_))) \# sys.path.append(BASEDIR) Host\_func\_dic = { 'disk':'func_demo.hosts.disk.Disk', 'mem':'func_demo.hosts.mem.Mem', 'cpu':'func_demo.hosts.cpu.Cpu', 'os':'func_demo.hosts.os.Os', 'ip':'func_demo.hosts.ip.Ip', } host_li=\['cpu','mem','ip'\] for host in host_li: path=Host\_func\_dic.get(host) module\_path,class\_name = path.rsplit('.',maxsplit=1) module = importlib.import\_module(module\_path) # from func_demo.hosts import disk # disk_class=getattr(disk,'Disk') disk\_class=getattr(module,class\_name) JG=disk_class() JG.run()
经过反射拿到 这个类