type()

type

isinstance() 与 type() 区别:

  • type() 不会认为子类是一种父类类型,不考虑继承关系。
  • isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()。

class A:
pass
class B(A):
pass
isinstance(A(), A)    # returns True
type(A()) == A        # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

用法

type(object)
type(name, bases, dict)
  • name -- 类的名称。
  • bases -- 基类的元组。
  • dict -- 字典,类内定义的命名空间变量。

一个参数返回对象类型, 三个参数,返回新的类型对象。

# 实例方法
def instancetest(self):
	print("this is a instance method")


# 类方法
@classmethod
def classtest(cls):
	print("this is a class method")


# 静态方法
@staticmethod
def statictest():
	print("this is a static method")


# 创建类
test_property = {"name": "tom", "instancetest": instancetest, "classtest": classtest, "statictest": statictest}
Test = type("Test", (), test_property)


# 创建对象
test = Test()
# 调用方法
print(test.name)
test.instancetest()
test.classtest()
test.statictest()

Type和Object

type为对象的顶点,所有对象都创建自type。

object为类继承的顶点,所有类都继承自object。

python中万物皆对象,一个python对象可能拥有两个属性,__class____base____class__ 表示这个对象是谁创建的,__base__ 表示一个类的父类是谁。

In [1]: object.__class__
Out[1]: type

In [2]: type.__base__
Out[2]: object

可以得出结论:

  • type类继承自object
  • object的对象创建自type
class A:
    pass
a = A()
print(a.__class__)   #<class '__main__.A'>

vars()

vars() 函数返回对象object的属性和属性值的字典对象。

>>> class Runoob:
...     a = 1
... 
>>> print(vars(Runoob))
{'a': 1, '__module__': '__main__', '__doc__': None}
posted @ 2020-07-23 09:35  friedCoder  阅读(197)  评论(0编辑  收藏  举报