软件测试学习 之 Python 新式类与旧式类

新式类:以object作为基类

python3默认以object作为基类,定义的类都是新式类

旧式类:不以object作为基类

python2不指定父类,则不会以object作为基类,称为旧类-经典类

通过dir函数可以查看对象的属性、方法列表

实例

以下实例展示了 dir 的使用方法:

>>> dir()  #  获得当前模块的属性列表
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> dir([]) #查看列表的属性和方法
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

比较object类和继承类的属性差异

In[8]: class ClassA(object):
  ...:     pass
  ...:
  ...:
  ...: o_dir=dir(object)
  ...: b_dir=dir(ClassA())
  ...: 
  ...: print(o_dir.__len__())
  ...: print(b_dir.__len__())
  ...: 
  ...: for item in o_dir:
  ...:     b_dir.remove(item) 
  ...: 
  ...: print(b_dir)
23
26
['__dict__', '__module__', '__weakref__']

猜你喜欢

转载自blog.csdn.net/jian3x/article/details/89041456