欢迎来到Louis的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

面向对象 3

类型判断
issubclass
判断类classA是否是类classB的子类
# issubclass(classA, classB)  判断类classA是否是类classB的子类,
#                             包括A和B有多层的继承关系也可判断,例如类B是类C的子类,那么类A也是类C的子类。

# issubclass(classA, (classB,classC,classD)) 判断类A是否是类B,C,D中任何一个类的子类,只要有一个成立则返回True
# def issubclass(x, A_tuple):  # real signature unknown; restored from __doc__
#     """
#     Return whether 'cls' is a derived from another class or is the same class.
#
#     A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
#     check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
#     or ...`` etc.
#     """
class Base(object):
    pass


class Foo1(Base):
    pass


class Foo2(Foo1):
    pass


class Foo3(Foo2):
    pass


class Other(object):
    pass


ret1 = issubclass(Foo3, Base)
print(ret1)

ret2 = issubclass(Foo3, Foo1)
print(ret2)

ret3 = issubclass(Foo3, Foo2)
print(ret3)

ret4 = issubclass(Foo3, object)
print(ret4)

ret5 = issubclass(Foo3, Other)
print(ret5)

ret6 = issubclass(Foo3, (str, list, tuple, dict, set))
print(ret6)

ret7 = issubclass(Foo3, (str, list, tuple, dict, set, Base))
print(ret7)

obj1 = Foo3()


#True
#True
#True
#True
#False
#False
#True
type
获取指定对象由那个类创建 | 获取指定对象的类型
# 获取指定对象由那个类创建 | 获取指定对象的类型
"""
class Foo(object):
    pass

obj1 = Foo()

if type(obj1) == Foo:
    print('obj是Foo类型')
"""
from types import FunctionType, MethodType


class Foo1(object):
    def __iter__(self, name):
        self.name = name

    def func1(self):
        print(self.name)

    @staticmethod
    def func2():
        print('staticmethod')


def func():
    pass


def counter(*args):
    count_func = 0
    count_meyhod = 0
    for item in args:
        if type(item) == FunctionType:
            count_func += 1
        elif type(item) == MethodType:
            count_meyhod += 1
    return count_func, count_meyhod


result = counter(Foo1().func1, Foo1().func2, func)
print(result)


#(2, 1)
isinstance
判断一个对象是否是指定的类型或者指定类型的父类创建的,接收两个参数,第一个参数为对象,第二个参数为类或者类组成的元组
# 判断一个对象是否是指定的类型或者指定类型的父类创建的,接收两个参数,第一个参数为对象,第二个参数为类或者类组成的元组
# s = 'abc'
# print(isinstance(s, str))
# lst = [1, 2, 3]
# print(isinstance(lst, (list, str, dict)))
class Base(object):
    pass


class Foo(Base):
    pass


class Foo1(Foo):
    pass


obj1 = Foo1()

print(isinstance(obj1, Foo))
print(isinstance(obj1, Foo1))
print(isinstance(obj1, Base))
print(isinstance(obj1, object))
print(isinstance(obj1, list))
print(isinstance(obj1, (list, str, dict)))
print(isinstance(obj1, (list, str, Foo)))

#True
#True
#True
#True
#False
#False
#True

 

posted on 2018-08-31 16:08  Louiszj  阅读(90)  评论(0编辑  收藏  举报

导航