导语:
本文主要介绍了关于python新式类是什么的相关知识,希望可以帮到处于编程学习途中的小伙伴
1、说明
python3.x的所有类,无论是否继承object,都会自动转为new-style类。
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
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python 的 id 函数是如何工作的12/29
- ♥ python if条件语句中如何进行多条件判断?10/05
- ♥ Python初学者的urlopen()详解10/06
- ♥ python os.system 执行cmd命令09/03
- ♥ 如何在python中拆分每隔几个字符10/26
- ♥ 为什么我劝你不要盲目追随Python?11/25
内容反馈