python3:的自省机制

自省的意思,自己反省自己,对自己进行刨析。例如论语中的名言:”吾日三省吾身”,没有经过自省的语言不是好语言。
编程中,自省的能力:检查某些事物以确定它是什么,它知道什么以及它能做什么。

1.联机帮助(help)

当我们对某个关键字和模块不是很熟悉,这个时候就可以向python发 救命(help),首先输入 help(),进行help 命令行 继续输入想要查的内容。

>>> help()
help>__dict__  #会得到官方说明
Help on dict object:

__dict__ = class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
-- More  --     #点击 enter 键可以继续知道详情

>>> help("str")    #同样也可以查到, 适用于模块查询
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |
-- More  --

2. dir()

上边的适用我们已经知道了 查找的内容,如果你连名称都不知道怎么办呢, 可以用dir(),可以查模块以及所有的对象类型
,简直无所不能。它返回传递给它的任何对象的属性名称经过排序的列表
如果不传入参数,它默认查找当前的作用域。

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>>

适用于所有的对象类型,例如字符串,数字,列表,类对象,类方法,元祖,字典,函数,定制类,例如传递数字
居然查到这么多属性。

>>> dir(int(5))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__'
, '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__po
s__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift_
_', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag'
, 'numerator', 'real', 'to_bytes']
>>>

3.__doc__文档描述

它包含了描述对象的注释,用__doc__.

>>> dir.__doc__
"dir([object]) -> list of strings\n\nIf called without an argument, return the names in the current scope.\nElse, return an alphabetized list of names comprising (some of) the attributes\nof the given object, and of
attributes reachable from it.\nIf the object supplies a method named __dir__, it will be used; otherwise\nthe default dir() logic is used and returns:\n  for a module object: the module's attributes.\n  for a class o
bject:  its attributes, and recursively the attributes\n    of its bases.\n  for any other object: its attributes, its class's attributes, and\n    recursively the attributes of its class's base classes."
>>>

4.检查Python 对象

我们通过以下几点进行介绍。

  • 对象的名称 用__name__
  • 对象的类型 用type() 最好用isinstance()
  • 对象知道什么用id()
  • 对象能做些什么用callable()
  • 对象的父对象是谁 用 issubclass()

对象名称

def a():
    pass
b=a
print(b.__name__)    #始终都会找到最初是的名称,中间的转化的不算。
a   

对象的类型
使用type(), 这里不讲述了, 在对象,类,type关系已经详细讲过了,他会返回一个对象类型,如下

def a():
    pass
b=a


print(type(a))
print(type(1))
#打印结果
<class 'function'>
<class 'int'>

对象知道什么 用ID

a=[1,2,3]
b=[1,2,3]

c=a
print(id(a))
print(id(b))
print(id(c))

print(a is b)
print(c is a)

print((a==b))

从结果来看, a is b 比较用的是ID ,a==b 比较用的value。

2933462198600
2933461439048
2933462198600
False
True
True

对象能做些什么用callable()****
这里指函数或方法的对象的可调用性。

def b():
    pass

print(callable(b))
print(callable(str)) #str 是一个内置方法,是可以调用。
#打印结果 
True 
True 

**对象的父对象是谁 用 issubclass()

class A:
    pass
class B(A):
    pass

class C(B):
    pass

print(C.__bases__) #查找父类
print(C.__mro__)# 寻找MRO 路线
print(issubclass(C,A))#比较是不是属于父类

打印结果

(<class '__main__.B'>,)
(<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
True

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值