当前位置: 移动技术网 > IT编程>脚本编程>Python > Python基于内置函数type创建新类型

Python基于内置函数type创建新类型

2020年10月23日  | 移动技术网IT编程  | 我要评论
英文文档:class type(object)class type(name, bases, dict)with one argument, return the type of an object.

英文文档:

class type(object)

class type(name, bases, dict)

with one argument, return the type of an object. the return value is a type object and generally the same object as returned by object.__class__.

the isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

with three arguments, return a new type object. this is essentially a dynamic form of the class statement. the namestring is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the __dict__ attribute.

  返回对象的类型,或者根据传入的参数创建一个新的类型

说明:

  1. 函数只传入一个参数时,返回参数对象的类型。 返回值是一个类型对象,通常与对象.__ class__返回的对象相同。

#定义类型a
>>> class a:
  name = 'defined in a'

#创建类型a实例a
>>> a = a()

#a.__class__属性
>>> a.__class__
<class '__main__.a'>

#type(a)返回a的类型
>>> type(a)
<class '__main__.a'>

#测试类型
>>> type(a) == a
true

 2. 虽然可以通过type函数来检测一个对象是否是某个类型的实例,但是更推荐使用isinstance函数,因为isinstance函数考虑了父类子类间继承关系。

#定义类型b,继承a
>>> class b(a):
  age = 2

#创建类型b的实例b
>>> b = b()

#使用type函数测试b是否是类型a,返回false
>>> type(b) == a
false

#使用isinstance函数测试b是否类型a,返回true
>>> isinstance(b,a)
true

 3. 函数另一种使用方式是传入3个参数,函数将使用3个参数来创建一个新的类型。其中第一个参数name将用作新的类型的类名称,即类型的__name__属性;第二个参数是一个元组类型,其元素的类型均为类类型,将用作新创建类型的基类,即类型的__bases__属性;第三个参数dict是一个字典,包含了新创建类的主体定义,即其值将复制到类型的__dict__属性中。

#定义类型a,含有属性infoa
>>> class a(object):
  infoa = 'some thing defined in a'

#定义类型b,含有属性infob
>>> class b(object):
  infob = 'some thing defined in b'

#定义类型c,含有属性infoc
>>> class c(a,b):
  infoc = 'some thing defined in c'

#使用type函数创建类型d,含有属性infod
>>> d = type('d',(a,b),dict(infod='some thing defined in d'))

#c、d的类型
>>> c
<class '__main__.c'>
>>> d
<class '__main__.d'>

#分别创建类型c、类型d的实例
>>> c = c()
>>> d = d()

#分别输出实例c、实例b的属性
>>> (c.infoa,c.infob,c.infoc)
('some thing defined in a', 'some thing defined in b', 'some thing defined in c')
>>> (d.infoa,d.infob,d.infod)
('some thing defined in a', 'some thing defined in b', 'some thing defined in d')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网