python新式类是什么?【python新式类用法】

353次阅读
没有评论

python新式类是什么?【python新式类用法】

什么是python新式类

python3.x的所有类都会自动转换为一个新式类,不论是否有继承object对象。

python2.x必须显式地指定类继承object父类才表示新式类。

python新式类实例

# 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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-30发表,共计884字。
新手QQ群:570568346,欢迎进群讨论 Python51学习