zoukankan      html  css  js  c++  java
  • [Python]利用type()动态创建类

     Python作为动态语言,可以动态地创建函数和类定义。比如说定义一个Hello类,就写一个hello.py模块:

    #! /usr/bin/env python
    #coding=utf-8
    class Hello(object):
        def hello(self,name='world'):
            print("Hello,%s"%name)

    当Python解释器载入hello模块时,会依次执行该模块的所有语句,执行的结果就是动态创建了一个Hello的class对象:

    from hello  import Hello
    h = Hello()
    h.hello()
    print( type(Hello))
    print (type(h))

    Hello,world
    <type 'type'>
    <class 'hello.Hello'>

    可以看到,Hello的class对象是type类型的,即Hello类是type()函数创建的。可以通过type()函数创建出Hello类,而无需class Hello(object)...这样的定义:

    def fn(self,name="world"):
        print("Hello,%s"%name)
    
    Hello = type('Hello',(object,),dict(hello=fn))
    h = Hello()
    h.hello()
    print(type(Hello))
    print(type(h))


    Hello,world
    <type 'type'>
    <class '__main__.Hello'>

    要动态创建一个class对象,type()函数依次传入3个参数:

    1、class的名称,字符串形式;

    2、继承的父类集合,注意Python支持多重继承,如果只有一个父类,注意tuple的单元素写法;

    3、class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上。

  • 相关阅读:
    231. Power of Two
    204. Count Primes
    205. Isomorphic Strings
    203. Remove Linked List Elements
    179. Largest Number
    922. Sort Array By Parity II
    350. Intersection of Two Arrays II
    242. Valid Anagram
    164. Maximum Gap
    147. Insertion Sort List
  • 原文地址:https://www.cnblogs.com/caoxing2017/p/8010695.html
Copyright © 2011-2022 走看看