• 1.类的两种创建方式(通过元类创建类)


    首先我们需要明确一点:python中,一切皆对象

    class Student:

      pass

    zhangsan = Student()

    对象有什么特点:

    1.可以被引用

    a = zhangsan

    2.可以当作函数参数输入

    func(zhangsan)

    3.可以当作函数的返回值

    def func():

      return zhangsan

    4.都可以当做容器的元素

    lis = ["hello, world", 1, zhangsan]

    而我们定义的类也都使用这些特点,我们把上述中的zhangsan换成Student也是可以的,由此得出结论:

    类也是对象!!!

    类既然是对象那么它一定是有某个类实例化得到的,这个类就是元类

    a = 5

    print(type(a))

    得到a是int类型

    print(type(type(a)))

    得到type类型,即int的类是type类,这个type就是我们要找的元类!

    类的类是元类,type类

     现在我们知道类也是通过元类实例化得到的,那么以后我们自己是不是也可以通过元类创建类呢?

    当然可以

    方法一:直接创建类

    class People:
        country = "China"
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def tell_info(self):
            print(f"{self.name} is from {self.country}, and he is {self.age} years old")
    
    
    chen = People("chenjun", 21)
    chen.tell_info()

    方法二:通过元类创建类
    首先,我们需要构成类的三要素,作为元类的参数

    参数1:类名,如上面的People

    参数2:类的基类(父类),python3中,如果没指定继承的类,则默认继承object类

    参数3:名称空间

    那么定义代码如下:

    class_name = "People"
    class_bases = (object,)
    class_dic = {}
    class_body = """
    country = "China"
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def tell_info(self):
        print(f"{self.name} is from {self.country}, and he is {self.age} years old")
    """
    exec(class_body, globals(), class_dic)
    People = type(class_name, class_bases, class_dic)
    chen = People("chenjun", 21)
    chen.tell_info()

     输出:

    chenjun is from China, and he is 21 years old
    
    ***Repl Closed***
  • 相关阅读:
    爬虫(七):爬取猫眼电影top100
    爬虫(六):Selenium库使用
    爬虫(五):PyQuery的使用
    爬虫(四):BeautifulSoup库的使用
    爬虫(三):Requests库的基本使用
    爬虫(一):基本原理
    爬虫(二):Urllib库详解
    安装mongodb
    利用 Chromium Embedded Framework (CEF) 定制提取 Flash 视频的浏览器
    Flash Player 19.0.0.124 Beta + IHTMLDocument3 IHTMLDocument2 ->get_innerHTML
  • 原文地址:https://www.cnblogs.com/tarantino/p/8955072.html
Copyright © 2020-2023  润新知