• 技术文章 >Python技术 >Python基础教程

    python新式类是什么

    小妮浅浅小妮浅浅2021-05-31 09:23:28原创1674

    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

    以上就是python新式类的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python新式类
    品易云
    上一篇:python可变参数的使用注意 下一篇:python响应头部是什么

    相关文章推荐

    • python multiprocessing如何使用?• python from…import的导入注意• python中__name__调用模块• dir()函数在python模块的使用• python中pip如何使用• python可变参数的使用注意

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网