zoukankan      html  css  js  c++  java
  • [py]python中__new__作用

    元类metaclass

    使劲搞,但是没搞清楚__new__的作用
    了解Python元类
    Python进阶:一步步理解Python中的元类metaclass

    Python中的__new__和__init__的区别

    使用元类

    __new__的作用: 元类

    class Author(type):
        # 类对象 类名 父类 类属性和方法
        def __new__(mcs, name, bases, dict):
            # 添加作者属性
            dict["author"] = "mm"
            return super(Author, mcs).__new__(mcs, name, bases, dict)
    
    class Foo(object, metaclass=Author):
        pass
    
    
    foo = Foo()
    print(foo.author)
    

    创建类

    def fn(self):
        print("maotai")
    
    
    # 类名 父类 属性
    Hello = type("Hello", (object,), dict(hello=lambda x: x + 1))
    h = Hello()
    h.hello(12)
    
    
    ## type
    # 1,同__class__, 实例属于哪一类 类属于哪一类
    # 2,创建一个类
    

    匿名函数

    g = lambda x: x + 1
    print(g(1))
    
    

    self是什么

    class A:
        # self是什么
        def __init__(self):
            print(self)
    
    a = A()
    print("--->",a)
    

    cls的含义

    class A:
        ## cls的含义
        @classmethod
        def show(cls,name):
            print("A",name)
    
    
    a = A()
    a.show("maota")
    

    子类调用父类方法super

    class A:
        def show(self):
            print("hello A")
    
    
    class B(A):
        def show2(self):
            super().show()  # 调用父类方法
    
    
    b = B()
    b.show2()
    

    类的属性和方法

    class A:
        age = 22
    
        def __init__(self):
            self.name = 'maotai'
        def show(self):
            pass
    
    ## dir(A) 有age, show         类的属性和方法
    ## dir(A()) 有name和age,show  实例的属性和方法
    
    for i in dir(A()):
        print(i)
    
    print(A.__dict__) # age show 类属性和方法
    # __doc__
    # __init__
    # __dict_
    # __dir__
    
    # __class__
    # __delattr__
    # __new__
    # __repr__
    # __setattr__
    

    @property和__call__ 与 callable()

    定制类

    
    class Person:
        # 对象当作属性来调用
        @property
        def show(self):
            print("mao tai")
        # 打印实例()时候的显示
        def __call__(self, *args, **kwargs):
            print("hello maotai")
    
    
    p = Person()
    # p()  # hello maotai
         # TypeError: 'Person' object is not callable
    p.show  # mao tai
    
    print(callable(p)) # True
    
  • 相关阅读:
    Activity
    日志
    StringBuffer
    内部类
    接口
    多态
    final关键字
    abstract关键字
    对象初始化
    继承
  • 原文地址:https://www.cnblogs.com/iiiiiher/p/8658864.html
Copyright © 2011-2022 走看看