object:所有类的"终极基类"
1. 基础特性:Python的类基础
object类是所有Python类的基类,提供了所有类实例共有的基本方法。当其构造器被调用时,它将返回一个新的基本对象。该构造器不接受任何参数。
# 创建基础对象实例
base_obj = object()
print(f"对象类型: {type(base_obj)}") # 输出: <class 'object'>
print(f"对象标识: {id(base_obj)}")
print(f"对象哈希: {hash(base_obj)}")
oct():八进制转换的"翻译器"
1. 基础用法:整数转八进制字符串
oct()函数将整数转换为带"0o"前缀的八进制字符串,是进制转换的重要工具。
# 基本八进制转换
print(f"8的八进制: {oct(8)}") # 输出: '0o10'
print(f"10的八进制: {oct(10)}") # 输出: '0o12'
print(f"16的八进制: {oct(16)}") # 输出: '0o20'
# 负数转换
print(f"-56的八进制: {oct(-56)}") # 输出: '-0o70'
print(f"0的八进制: {oct(0)}") # 输出: '0o0'
# 大整数转换
large_num = 2**20
print(f"2^20的八进制: {oct(large_num)}")
# 从十六进制数转换
hex_num = 0xFF
print(f"0xFF的八进制: {oct(hex_num)}") # 输出: '0o377'
# 使用__index__方法的对象
class IndexableNumber:
def __index__(self):
return 100
custom_obj = IndexableNumber()
print(f"自定义对象转换: {oct(custom_obj)}") # 输出: '0o144'
2. 实际应用:文件权限和进制转换工具
class PermissionConverter:
"""权限转换工具类(常用于Linux文件权限)"""
@staticmethod
def chmod_to_octal(permission_str):
"""将chmod权限字符串转换为八进制数字"""
if len(permission_str) != 9:
raise ValueError("权限字符串必须是9个字符")
# 权限映射:r=4, w=2, x=1
perms = {'r': 4, 'w': 2, 'x': 1, '-': 0}
# 每3位一组转换为八进制
result = 0
for i in range(0, 9, 3):
group = permission_str[i:i+3]
value = 0
for char in group:
if char in perms:
value += perms[char]
else:
raise ValueError(f"无效权限字符: {char}")
result = result * 10 + value # 注意:这里构建的是十进制数,但每位代表八进制值
return int(str(result), 8) # 将字符串解析为八进制整数
@staticmethod
def octal_to_chmod(octal_permission):
"""将八进制权限转换为chmod字符串"""
# 确保是有效的八进制权限(0-777)
if not 0 <= octal_permission <= 0o777:
raise ValueError("权限必须在0-777范围内")
permission_str = ""
# 转换为三位八进制字符串
oct_str = oct(octal_permission)[2:].zfill(3)
for digit in oct_str:
value = int(digit, 8)
# 转换为rwx格式
bits = [
'r' if value & 4 else '-',
'w' if value & 2 else '-',
'x' if value & 1 else '-'
]
permission_str += ''.join(bits)
return permission_str
@staticmethod
def format_octal_number(num, width=0, prefix=True):
"""格式化八进制输出"""
if prefix:
oct_str = oct(num)
else:
oct_str = format(num, 'o')
if width > 0:
# 处理前缀
if prefix and oct_str.startswith('0o'):
oct_str = '0o' + oct_str[2:].zfill(width)
elif prefix and oct_str.startswith('-0o'):
oct_str = '-0o' + oct_str[3:].zfill(width)
elif oct_str.startswith('-'):
oct_str = '-' + oct_str[1:].zfill(width)
else:
oct_str = oct_str.zfill(width)
return oct_str
# 使用示例
converter = PermissionConverter()
# 文件权限转换
print("=== 文件权限转换示例 ===")
permission_str = "rwxr-xr--"
octal_perm = converter.chmod_to_octal(permission_str)
print(f"权限 '{permission_str}' -> 八进制: {oct(octal_perm)}")
# 反向转换
converted_back = converter.octal_to_chmod(octal_perm)
print(f"八进制 {oct(octal_perm)} -> 权限: {converted_back}")
# 常见权限示例
common_permissions = {
"完全开放": 0o777, # rwxrwxrwx
"用户读写执行,组只读,其他无": 0o740, # rwxr-----
"用户读写,组只读,其他只读": 0o644, # rw-r--r--
"仅用户读写": 0o600, # rw-------
}
for name, perm in common_permissions.items():
perm_str = converter.octal_to_chmod(perm)
print(f"{name}: {oct(perm)} -> {perm_str}")
# 八进制格式化
test_numbers = [8, 10, 16, 100]
for num in test_numbers:
formatted = converter.format_octal_number(num, width=4, prefix=True)
print(f"{num} 的八进制: {formatted}")
ord():字符编码的"解码器"
1. 基础用法:获取字符的Unicode码位
ord()函数返回字符的Unicode码位(整数),是字符编码处理的基础。
# 基本ASCII字符
print(f"'a'的码位: {ord('a')}") # 输出: 97
print(f"'A'的码位: {ord('A')}") # 输出: 65
print(f"'0'的码位: {ord('0')}") # 输出: 48
print(f"' '的码位: {ord(' ')}") # 输出: 32(空格)
# 特殊字符
print(f"'€'的码位: {ord('€')}") # 输出: 8364(欧元符号)
print(f"'中'的码位: {ord('中')}") # 输出: 20013
print(f"'☆'的码位: {ord('☆')}") # 输出: 9734
# 控制字符
print(f"'\\n'的码位: {ord('\\n')}") # 输出: 10(换行符)
print(f"'\\t'的码位: {ord('\\t')}") # 输出: 9(制表符)
# 字节对象(单字节)
print(f"b'a'的码位: {ord(b'a')}") # 输出: 97
print(f"b'\\x41'的码位: {ord(b'\\x41')}") # 输出: 65(ASCII 'A')
# bytearray对象
ba = bytearray(b'X')
print(f"bytearray的码位: {ord(ba)}") # 输出: 88
2. 实际应用:字符编码分析和转换
class CharacterAnalyzer:
"""字符分析工具类"""
@staticmethod
def analyze_string(text):
"""分析字符串中所有字符的编码信息"""
results = []
for i, char in enumerate(text):
code_point = ord(char)
results.append({
'index': i,
'character': char,
'codepoint': code_point,
'hex': hex(code_point),
'binary': bin(code_point),
'category': CharacterAnalyzer.get_char_category(char)
})
return results
@staticmethod
def get_char_category(char):
"""获取字符类别"""
code = ord(char)
if 0 <= code <= 31:
return "控制字符"
elif 32 <= code <= 126:
return "ASCII可打印字符"
elif 127 <= code <= 255:
return "扩展ASCII"
elif 256 <= code <= 65535:
return "基本多文种平面(BMP)"
else:
return "补充平面"
@staticmethod
def string_to_codepoints(text, format='decimal'):
"""将字符串转换为码点序列"""
codepoints = [ord(c) for c in text]
if format == 'decimal':
return codepoints
elif format == 'hex':
return [hex(cp) for cp in codepoints]
elif format == 'binary':
return [bin(cp) for cp in codepoints]
else:
return codepoints
@staticmethod
def codepoints_to_string(codepoints):
"""将码点序列转换回字符串"""
return ''.join(chr(cp) for cp in codepoints)
@staticmethod
def find_special_characters(text):
"""查找文本中的特殊字符"""
special_chars = []
for char in text:
cp = ord(char)
if cp < 32 or cp > 126: # 非标准ASCII字符
special_chars.append({
'char': char,
'codepoint': cp,
'representation': repr(char)
})
return special_chars
# 使用示例
analyzer = CharacterAnalyzer()
# 字符串分析
print("=== 字符串编码分析 ===")
test_text = "Hello 世界! ☆"
analysis = analyzer.analyze_string(test_text)
for item in analysis:
print(f"位置 {item['index']}: '{item['character']}' -> "
f"码点 {item['codepoint']}, 十六进制 {item['hex']}, "
f"类别: {item['category']}")
# 码点转换
codepoints_decimal = analyzer.string_to_codepoints("ABC", format='decimal')
codepoints_hex = analyzer.string_to_codepoints("ABC", format='hex')
print(f"字符串码点(十进制): {codepoints_decimal}")
print(f"字符串码点(十六进制): {codepoints_hex}")
# 反向转换
original = analyzer.codepoints_to_string([72, 101, 108, 108, 111])
print(f"码点转字符串: {original}")
# 查找特殊字符
text_with_special = "Hello\tWorld\n中国☆"
special = analyzer.find_special_characters(text_with_special)
print(f"\n特殊字符查找:")
for item in special:
print(f" 字符: {item['representation']}, 码点: {item['codepoint']}")
总结
本文详细解析了Python中三个重要的内置功能:
- 1. object - 所有类的终极基类,基类设计、内存优化、不可变对象
- 2. oct(integer) - 八进制转换的翻译器,文件权限管理、进制转换、低级编程
- 3. ord(character) - 字符编码的解码器,字符编码分析、文本处理、国际化支持
关键知识点总结:
- •
object是所有Python类的基类,实例没有__dict__属性 - •
oct()将整数转换为带"0o"前缀的八进制字符串 - •
ord()返回字符的Unicode码位,支持字符串和字节对象