1、说明
python3.x的所有类都会自动转换为一个新式类,不论是不是有继承object对象。
python2.x必要显式地指定类继承object父类才暗示新式类。
2、实例
# newstyle.py,python环境为2.xclass Classic:
"""
python2.x默认类为经典类
因为__getatt__ 与 __getattribute__功能效果同样,这儿只用__getattr__演示
"""
def __getattr__(self, method_name):
print("call Classic __getattr__,it would call built-in[%s] method " % method_name) return getattr(self.__name,method_name)class NewStyleClass(object): def __init__(self):
self.__name = "newstyle name"
"""
python2.x必须指明为新式类,python3.x默认为新式类
"""
def __getattr__(self, item):
print("call NewStyle __getattr__,it would call built-in[%s] method " %item) return getattr(self.__name,item)def test_dir():
C = Classic()
N = NewStyleClass()
print(dir(C) # 经典类内置有__getattr__办法
print(dir(N) # 新式类的内置办法继承object对象>>> python newstyle.py返回外链论坛:www.fok120.com,查看更加多
责任编辑:网友投稿
|