Python编程
Completion requirements
Python 脚本可以了解对象的类型、类、属性和方法。这被称为反射或自省。另请参见元类(Metaclasses)。
反射启用函数包括 type()
、isinstance()
、callable()
、dir()
和 getattr()
。
类型
type
方法用于获取对象的类型。以下测试会返回 True:
type(3) is int
type(3.0) is float
type(10**10) is long # Python 2
type(1 + 1j) is complex
type('Hello') is str
type([1, 2]) is list
type([1, [2, 'Hello']]) is list
type({'city': 'Paris'}) is dict
type((1,2)) is tuple
type(set()) is set
type(frozenset()) is frozenset
type(3).__name__ == "int"
type('Hello').__name__ == "str"
导入 types
和 re
模块后的示例:
import types, re, Tkinter # For the following examples
type(re) is types.ModuleType
type(re.sub) is types.FunctionType
type(Tkinter.Frame) is types.ClassType
type(Tkinter.Frame).__name__ == "classobj"
type(Tkinter.Frame()).__name__ == "instance"
type(re.compile('myregex')).__name__ == "SRE_Pattern"
type(type(3)) is types.TypeType
type
函数不考虑类的继承关系:“type(3) is object”返回 False,而“isinstance(3, object)”返回 True。
参考链接:
isinstance
isinstance
用于确定一个对象是否是某个类型或类的实例。
以下测试会返回 True:
isinstance(3, int)
isinstance([1, 2], list)
isinstance(3, object)
isinstance([1, 2], object)
import Tkinter; isinstance(Tkinter.Frame(), Tkinter.Frame)
import Tkinter; Tkinter.Frame().__class__.__name__ == "Frame"
isinstance
提供的条件比直接使用 type
更弱。
自定义类 isinstance
示例:
class Plant: pass # 空类
class Tree(Plant): pass # 从 Plant 派生的类
tree = Tree() # Tree 类的一个新实例
print(isinstance(tree, Tree)) # True
print(isinstance(tree, Plant)) # True
print(isinstance(tree, object)) # True
print(type(tree) is Tree) # True
print(type(tree).__name__ == "instance") # False
print(tree.__class__.__name__ == "Tree") # True
参考链接:
issubclass
issubclass
用于确定一个类是否是另一个类的子类。它适用于类,而非类的实例。
class Plant: pass # 空类
class Tree(Plant): pass # 从 Plant 派生的类
tree = Tree() # Tree 类的一个新实例
print(issubclass(Tree, Plant)) # True
print(issubclass(Tree, object)) # False 在 Python 2 中
print(issubclass(int, object)) # True
print(issubclass(bool, int)) # True
print(issubclass(int, int)) # True
print(issubclass(tree, Plant)) # 错误 - tree 不是类
参考链接:
鸭子类型
鸭子类型提供了一种间接的反射手段。它是一种技术,通过将对象作为请求类型来使用,同时捕获由于对象不支持某些类或类型的特性而导致的异常。
参考链接:
callable
callable
用于判断一个对象是否可以被调用。通过提供 __call__()
方法,类可以变得可调用。
示例:
callable(2) # 返回 False,类似于 callable("Hello") 和 callable([1, 2])
callable([1,2].pop) # 返回 True,因为没有 "()" 时,pop 返回的是一个函数对象
callable([1,2].pop()) # 返回 False,因为 [1,2].pop() 返回的是 2 而不是一个函数对象
参考链接:
dir
返回对象的属性名称列表,包括方法。根据 Python.org,它是一个启发式的函数,可能不完全准确。
示例:
dir(3)
dir("Hello")
dir([1, 2])
import re; dir(re) # 列出 re 模块中的函数和其他对象
参考链接:
getattr
返回对象的属性值,属性名称作为字符串传递。
示例:
getattr(3, "imag")
对象的属性列表可以使用 dir()
获得。
参考链接:
关键词
可以从 Python 中获取关键词列表:
import keyword
pykeywords = keyword.kwlist
print(keyword.iskeyword("if")) # True
print(keyword.iskeyword("True")) # False
参考链接:
内建对象
可以从 Python 获取内建对象和函数列表:
print(dir(__builtins__)) # 输出列表
print(type(__builtins__.list)) # = <type 'type'>
print(type(__builtins__.open)) # = <type 'builtin_function_or_method'>
print(list is __builtins__.list) # True
print(open is __builtins__.open) # True
Last modified: Friday, 31 January 2025, 1:06 AM