首页 > 编程语言 > 详细

Python 面向对象编程——获取对象信息

时间:2016-07-14 07:15:38      阅读:289      评论:0      收藏:0      [点我收藏+]

1.1   获取对象信息

1.1.1   使用type()判断对象类型

>>> type(123)    --基本数据类型判断

<class ‘int‘>

>>> type(‘123‘)

<class ‘str‘>

>>> type(abs)    --python内置函数的判断

<class ‘builtin_function_or_method‘>

>>> type(Dog)

<class ‘type‘>

>>> type(Dog())    --自定义类的判断,引自上文中的Dogclass

<class ‘__main__.Dog‘>

 

>>> type(123) == type(456)

True

>>> type(‘123‘) == type(‘456‘) #可以在if中判断

True

判断对象是否是函数,types模块中的常量

>>> importtypes

>>> def fn():

...    pass

...

>>> type(fn) == types.FunctionType

True

>>> type(abs) ==types.BuiltinFunctionType

True

>>> type(lambda x:x) ==types.LambdaType

True

>>> type((x for x in range(10)))== types.GeneratorType

True

1.1.2   使用isinstance()判断继承

>>> class Animal(object):

...    pass

...

>>> class Dog(Animal):

...    pass

...

>>> class Erha(Dog):

...    pass

...

>>> # object -> Animal ->Dog -> Erha 继承关系

... a = Animal()     #依次创建对象

>>> b = Dog()

>>> c = Erha()

>>>

>>> isinstance(c,Erha)

True

>>> isinstance(c, Dog)

True

>>> isinstance(c, Animal)

True

>>> isinstance(b, Dog)

True

>>> isinstance(b, Animal)

True

>>> isinstance(b, Erha)

False

能用type()判断也可以用isinstance判断

>>> isinstance(123, int)

True

>>> isinstance(‘a‘, str)

True

>>> isinstance([1,2, 3], (list, tuple))    --判断一个变量是否是某些类型中的一种

True

>>> isinstance((1, 2, 3), (list,tuple))

True

1.1.3   使用dir()获取对象的属性和方法

>>> dir(‘abc‘)    --列出属性和方法

[‘__add__‘, ‘__class__‘, ‘__contains__‘,‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘,‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘,‘__init__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘,‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘,‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘,‘capitalize‘, ‘casefold‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘,‘expandtabs‘, ‘find‘, ‘format‘, ‘format_map‘, ‘index‘, ‘isalnum‘, ‘isalpha‘,‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘,‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘,‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘,‘rsplit‘, ‘rstrip‘, ‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘,‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]

配合getattr()setattr()以及hasattr(),我们可以直接操作一个对象的状态。

>>> class Myobject(object):

...    def __init__(self):

...        self.x = 9

...    def power(self):

...        return self.x * self.x

...

>>> obj = Myobject()

>>> hasattr(obj,‘x‘)    #有属性‘x‘

True

>>> obj.x

9

>>> getattr(obj,‘x‘)

9

>>> hasattr(obj, ‘y‘)    #有属性‘y‘?

False

>>> setattr(obj,‘y‘, 19)    #设置一个y属性为19

>>> getattr(obj, ‘y‘)

19

>>> obj.y

19

>>> hasattr(obj, ‘power‘)      #有属性power(方法)?

True

>>> getattr(obj, ‘power‘)      #获取属性power

<bound method Myobject.power of<__main__.Myobject object at 0x2af174d0bd68>>

SyntaxError: invalid character inidentifier

>>> getattr(obj, ‘power‘)()      #获取属性power

81

>>> fn = getattr(obj, ‘power‘)

>>> fn()

81

hasattr的经典应用场景

应用上述的Myobject()实例

>>> def readPower(obj):

...    if hasattr(obj, ‘power‘):

...         return obj.power()

...    else:

...        return None

...

>>> readPower(Myobject)

Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

 File "<stdin>", line 3, in readPower

TypeError: power() missing 1 requiredpositional argument: ‘self‘

>>> Myobject().x

9

>>> Myobject().power()

81

>>> readPower(Myobject())

81


本文出自 “90SirDB” 博客,请务必保留此出处http://90sirdb.blog.51cto.com/8713279/1826206

Python 面向对象编程——获取对象信息

原文:http://90sirdb.blog.51cto.com/8713279/1826206

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!