IT类作者联盟python 集

python 面向对象编程之获取对象信息

2019-07-05  本文已影响15人  Swift社区

python学习笔记,特做记录,分享给大家,希望对大家有所帮助。

获取对象信息

当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?

使用type()

首先,我们来判断对象类型,使用type()函数:

基本类型都可以用type()判断:

print type(1234)
print type('str')
print type(None)

运行结果:

<type 'int'>
<type 'str'>
<type 'NoneType'>

Process finished with exit code 0

如果一个变量指向函数或者类,也可以用type()判断:

print type(abs)
a = list()
print type(a)

运行结果:

<type 'builtin_function_or_method'>
<type 'list'>

Process finished with exit code 0

但是type()函数返回的是什么类型呢?它返回对应的Class类型。如果我们要在if语句中判断,就需要比较两个变量的type类型是否相同:

print type(123)==type(456)
print type(123)==int
print type('abc')==type('123')
print type('abc')==str
print type('abc')==type(123)

运行结果:

True
True
True
True
False

Process finished with exit code 0

判断基本数据类型可以直接写int,str等,但如果要判断一个对象是否是函数怎么办?可以使用types模块中定义的常量:

import types
def fn():
    pass
print type(fn)==types.FunctionType
print type(abs)==types.BuiltinFunctionType
print type(lambda  x: x)==types.LambdaType
print type((x for x in range(10)))==types.GeneratorType

运行结果:

True
True
True
True

Process finished with exit code 0

使用isinstance()

对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数。

我们回顾上次的例子,如果继承关系是:

object -> Animal -> Dog -> Husky

源代码如下:

class Animal(object):
    def run(self):
        print 'Animal is running...'

class Dog(Animal):
    def run(self):
        print 'Dog is running...'

    def eat(self):
        print 'Eating meat...'

class Husky(Dog):
    def run(self):
        print 'Husky is running...'

那么,isinstance()就可以告诉我们,一个对象是否是某种类型。先创建3种类型的对象:

a = Animal()
d = Dog()
h = Husky()

然后,判断:

print isinstance(h, Husky)

运行结果:

True

Process finished with exit code 0

没有问题,因为h变量指向的就是Husky对象。

再判断:

print isinstance(h, Dog)

运行结果:

True

Process finished with exit code 0

h虽然自身是Husky类型,但由于Husky是从Dog继承下来的,所以,h也还是Dog类型。换句话说,isinstance()判断的是一个对象是否是该类型本身,或者位于该类型的父继承链上。

因此,我们可以确信,h还是Animal类型:

print isinstance(h, Animal)

运行结果:

True

Process finished with exit code 0

同理,实际类型是Dog的d也是Animal类型:

print isinstance(d, Dog) and isinstance(d, Animal)

运行结果:

True

Process finished with exit code 0

但是,d不是Husky类型:

print isinstance(d, Husky)

运行结果:

False

Process finished with exit code 0

能用type()判断的基本类型也可以用isinstance()判断:

print isinstance('a', str)
print isinstance(123, int)
print isinstance(b'a', bytes)

运行结果:

True
True
True

Process finished with exit code 0

并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是list或者tuple:

print isinstance([1, 2, 3], (list, tuple))
print isinstance((1, 2, 3), (list, tuple))

运行结果:

True
True

Process finished with exit code 0

总是优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”。

使用dir()

如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法:

print dir('ABC')

运行结果:

['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']

Process finished with exit code 0

类似xxx的属性和方法在Python中都是有特殊用途的,比如len方法返回长度。在Python中,如果你调用len()函数试图获取一个对象的长度,实际上,在len()函数内部,它自动去调用该对象的len()方法,所以,下面的代码是等价的:

print len('ABC')
print 'ABC'.__len__()

运行结果:

3
3

Process finished with exit code 0

我们自己写的类,如果也想用len(myObj)的话,就自己写一个len()方法:

class MyDog(object):
    def __len__(self):
        return 100
dog = MyDog()
print len(dog)

运行结果:

100

Process finished with exit code 0

剩下的都是普通属性或方法,比如lower()返回小写的字符串:

print 'ABC'.lower()

运行结果:

abc

Process finished with exit code 0

仅仅把属性和方法列出来是不够的,配合getattr()、setattr()以及hasattr(),我们可以直接操作一个对象的状态:

class MyObject(object):
    def __init__(self):
        self.x = 9
    def power(self):
        return self.x * self.x
obj = MyObject()

紧接着,可以测试该对象的属性:

print hasattr(obj, 'x') # 有属性'x'吗?
print obj.x
print hasattr(obj, 'y') # 有属性'y'吗?
print setattr(obj, 'y', 19) # 设置一个属性'y'
print hasattr(obj, 'y') # 有属性'y'吗?
print getattr(obj, 'y') # 获取属性'y'
print obj.y # 获取属性'y'

运行结果:

True
9
False
None
True
19
19

Process finished with exit code 0

如果试图获取不存在的属性,会抛出AttributeError的错误:

print getattr(obj, 'z') # 获取属性'z'

运行结果:

line 86, in <module>
    print getattr(obj, 'z') # 获取属性'z'
AttributeError: 'MyObject' object has no attribute 'z'

Process finished with exit code 1

可以传入一个default参数,如果属性不存在,就返回默认值:

print getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404

运行结果:

404

Process finished with exit code 0

也可以获得对象的方法:

print hasattr(obj, 'power') # 有属性'power'吗?
print getattr(obj, 'power') # 获取属性'power'
fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn
print fn # fn指向obj.power
print fn() # 调用fn()与调用obj.power()是一样的

运行结果:

True
<bound method MyObject.power of <__main__.MyObject object at 0x105150e90>>
<bound method MyObject.power of <__main__.MyObject object at 0x105150e90>>
81

Process finished with exit code 0

欢迎关注公众号「网罗开发」,回复 「python」 可领取python测试demo和学习资源,大家一起学python,网罗天下方法,方便你我开发

希望可以帮助大家,如有问题可加QQ技术交流群: 668562416
如果哪里有什么不对或者不足的地方,还望读者多多提意见或建议
如需转载请联系我,经过授权方可转载,谢谢


欢迎关注公众号「网罗开发」

image
上一篇 下一篇

猜你喜欢

热点阅读