小白学python之获取对象信息_学习笔记

本文以廖雪峰的官方网站为参考来学习python的。其学习链接为廖雪峰小白学python教程

本文是学习到python的获取对象信息。参考链接廖雪峰python获取对象信息

使用type()

print(type(123))
print(type('str'))
print(type(None))
print(type(abs))

运行结果为:

<class 'int'>
<class 'str'>
<class 'NoneType'>
<class 'builtin_function_or_method'>

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
 

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

运行结果为:

<class 'function'>
True
<class 'builtin_function_or_method'>
True
<class 'function'>
True
<class 'generator'>
True
 

使用isinstance()

笔记

下面的代码就可以判断是否是list或者tuple:

print(isinstance('a',str))
print(isinstance(123,int))
print(isinstance(b'a',bytes))
print(isinstance([1,2,3],(list,tuple)))
print(isinstance((1,2,3),(list,tuple)))

运行结果为:

True
True
True
True
True

使用dir()

print(dir('ABC'))
print(len('ABC'))
print('ABC'.__len__())
class MyDog(object):
    def __len__(self):
        return 100
dog = MyDog()
print(len(dog))
print('ABC'.lower())

运行结果为:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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', 'isascii', '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']
3
3
100
abc

笔记:

配合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'))
print(obj.x)
print(hasattr(obj, 'y'))
setattr(obj, 'y', 19)
print(hasattr(obj, 'y'))
print(getattr(obj,'y'))
print(obj.y)

运行结果:

True
9
False
True
19
19

笔记

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

运行

getattr(obj,'z')

则会报错:

Traceback (most recent call last):
  File "**********", line ***, in <module>
    getattr(obj,'z')
AttributeError: 'MyObject' object has no attribute 'z'

笔记

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

运行:

print(getattr(obj,'z',404))

结果:

404

print(hasattr(obj,'power'))
print(getattr(obj,'power'))
fn = getattr(obj, 'power')
print(fn)
print(fn())

运行结果:

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

小结看不懂,没有使用过。

def readImage(fp):
    if hasattr(fp,'read'):
        return readData(fp)
    return None 

猜你喜欢

转载自blog.csdn.net/u010352129/article/details/83991841