当前位置:首页>python>Python 内置函数系列:c开头系列函数

Python 内置函数系列:c开头系列函数

  • 2026-10-26 21:16:29
Python 内置函数系列:c开头系列函数

callable():判断对象是否"可调用"

1. 基本用法

callable()函数就像是一个"能力检测器",它可以判断一个对象是否可以被调用(即是否可以使用括号()来执行)。

# 检测不同类型对象的可调用性
def
 normal_function():
    return
 "我是一个函数"

class
 MyClass:
    def
 __init__(self):
        self
.name = "示例类"

# 测试各种对象

print
(callable(normal_function))  # True - 函数是可调用的
print
(callable(MyClass))         # True - 类是可调用的(调用类会创建实例)
print
(callable(MyClass()))        # False - 默认实例不可调用

# 添加__call__方法后,让实例可调用

class
 CallableClass:
    def
 __call__(self):
        return
 "现在我可以被调用了!"

callable_instance = CallableClass()
print
(callable(callable_instance))  # True
print
(callable_instance())          # "现在我可以被调用了!"

2. 实际应用场景

# 动态调用验证
def
 safe_call(func, *args, **kwargs):
    """安全调用函数,避免AttributeError"""

    if
 callable(func):
        return
 func(*args, **kwargs)
    else
:
        raise
 TypeError(f"对象 {func} 不可调用")

# 插件系统中的应用

class
 PluginSystem:
    def
 __init__(self):
        self
.plugins = []

    def
 register_plugin(self, plugin):
        """注册插件,确保插件有call方法"""

        if
 callable(plugin):
            self
.plugins.append(plugin)
        else
:
            print
(f"警告: {plugin} 不是可调用对象,无法注册")

    def
 run_all(self):
        """运行所有插件"""

        for
 plugin in self.plugins:
            if
 callable(plugin):
                plugin()

# 使用示例

def
 simple_plugin():
    print
("简单插件执行")

system = PluginSystem()
system.register_plugin(simple_plugin)  # 成功注册
system.register_plugin("不是函数")      # 会发出警告

chr():数字到字符的"翻译官"

1. 基础字符转换

chr()函数将Unicode码点转换为对应的字符,是ord()函数的逆操作。

# 基本ASCII字符
print
(chr(65))    # 'A' - 大写A
print
(chr(97))    # 'a' - 小写a
print
(chr(48))    # '0' - 数字0

# 特殊符号和表情

print
(chr(169))   # '©' - 版权符号
print
(chr(8364))  # '€' - 欧元符号
print
(chr(128512)) # '😀' - 笑脸表情

# 实用范围示例

for
 code in range(65, 91):  # A-Z
    print
(chr(code), end=' ')
# 输出: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

2. 实际应用:密码生成器

import random

def
 generate_password(length=8, use_special_chars=True):
    """生成随机密码"""

    password = []

    # 数字范围

    numbers = [chr(i) for i in range(48, 58)]  # 0-9

    # 小写字母

    lower_case = [chr(i) for i in range(97, 123)]  # a-z

    # 大写字母  

    upper_case = [chr(i) for i in range(65, 91)]  # A-Z

    # 特殊字符

    special_chars = [chr(33), chr(35), chr(36), chr(37), chr(38)]  # ! # $ % &

    # 组合所有字符

    all_chars = numbers + lower_case + upper_case
    if
 use_special_chars:
        all_chars.extend(special_chars)

    # 生成密码

    for
 _ in range(length):
        password.append(random.choice(all_chars))

    return
 ''.join(password)

# 生成密码示例

print
(f"简单密码: {generate_password(6, use_special_chars=False)}")
print
(f"复杂密码: {generate_password(12, use_special_chars=True)}")

@classmethod:面向类的"团队协作"

1. 基本概念和使用

类方法将方法绑定到类而不是实例,第一个参数是类本身(通常命名为cls)。

class Date:
    def
 __init__(self, year, month, day):
        self
.year = year
        self
.month = month
        self
.day = day

    @classmethod

    def
 from_string(cls, date_string):
        """从字符串创建Date实例"""

        year, month, day = map(int, date_string.split('-'))
        return
 cls(year, month, day)  # 相当于调用Date(year, month, day)

    @classmethod

    def
 from_timestamp(cls, timestamp):
        """从时间戳创建Date实例(模拟)"""

        # 简化实现,实际中会使用datetime库

        return
 cls(2024, 1, 1)  # 返回固定日期

    def
 __str__(self):
        return
 f"{self.year}-{self.month:02d}-{self.day:02d}"

# 使用不同的构造方法

date1 = Date(2024, 1, 15)  # 传统构造
date2 = Date.from_string("2024-01-20")  # 类方法构造
date3 = Date.from_timestamp(1642204800)  # 另一个类方法

print
(f"日期1: {date1}")
print
(f"日期2: {date2}")
print
(f"日期3: {date3}")

2. 实际应用:工厂模式

class Animal:
    def
 __init__(self, name, sound):
        self
.name = name
        self
.sound = sound

    @classmethod

    def
 create_dog(cls):
        """创建狗实例的工厂方法"""

        return
 cls("狗", "汪汪")

    @classmethod

    def
 create_cat(cls):
        """创建猫实例的工厂方法"""

        return
 cls("猫", "喵喵")

    @classmethod

    def
 create_animal(cls, animal_type):
        """通用动物工厂"""

        animals = {
            'dog'
: ("狗", "汪汪"),
            'cat'
: ("猫", "喵喵"),
            'duck'
: ("鸭子", "嘎嘎")
        }
        if
 animal_type in animals:
            name, sound = animals[animal_type]
            return
 cls(name, sound)
        else
:
            raise
 ValueError(f"不支持的动物类型: {animal_type}")

    def
 speak(self):
        return
 f"{self.name}说: {self.sound}"

# 使用工厂方法创建对象

dog = Animal.create_dog()
cat = Animal.create_cat()
duck = Animal.create_animal('duck')

print
(dog.speak())  # 狗说: 汪汪
print
(cat.speak())  # 猫说: 喵喵
print
(duck.speak()) # 鸭子说: 嘎嘎

compile():代码的"编译器"

1. 基础编译功能

compile()函数将源代码字符串编译为可执行的代码对象或AST对象。

# 编译简单表达式
code_str = "x + y * 2"
compiled_code = compile(code_str, '<string>', 'eval')

# 执行编译后的代码

x, y = 5, 3
result = eval(compiled_code)
print
(f"表达式结果: {result}")  # 5 + 3 * 2 = 11

# 编译多行代码(语句序列)

multi_line_code = """
for i in range(3):
    print(f"数字: {i}")
"""

compiled_exec = compile(multi_line_code, '<string>', 'exec')
exec
(compiled_exec)

2. 实际应用:简单公式计算器

def safe_calculator(expression, variables=None):
    """安全的公式计算器"""

    if
 variables is None:
        variables = {}

    try
:
        # 编译表达式为eval模式

        compiled = compile(expression, '<calculator>', 'eval')

        # 安全地执行(限制可用变量)

        allowed_vars = {'__builtins__': None}  # 限制内置函数
        allowed_vars.update(variables)

        result = eval(compiled, allowed_vars)
        return
 result
    except
 SyntaxError as e:
        return
 f"公式语法错误: {e}"
    except
 Exception as e:
        return
 f"计算错误: {e}"

# 使用示例

variables = {'a': 10, 'b': 5, 'c': 2}

expressions = [
    "a + b * c"
,        # 正常计算
    "(a + b) * c"
,      # 带括号
    "max(a, b, c)"
,     # 会报错(max被限制)
    "invalid syntax"
    # 语法错误
]

for
 expr in expressions:
    result = safe_calculator(expr, variables)
    print
(f"{expr} = {result}")

complex():复数的"创造者"

1. 多种创建方式

complex()函数提供了多种创建复数的方式,非常灵活。

# 方式1:从字符串创建
c1 = complex("3+4j")
print
(f"从字符串: {c1}")  # (3+4j)

# 方式2:分别指定实部和虚部

c2 = complex(3, 4)
print
(f"分别指定: {c2}")  # (3+4j)

# 方式3:只指定实部或虚部

c3 = complex(5)        # 实部为5,虚部为0
c4 = complex(imag=7)  # 实部为0,虚部为7
print
(f"只有实部: {c3}")  # (5+0j)
print
(f"只有虚部: {c4}")  # 7j

# 方式4:从其他数字类型转换

c5 = complex(3.14)    # 浮点数转复数
print
(f"浮点转换: {c5}")  # (3.14+0j)

2. 实际应用:复数运算工具

class ComplexCalculator:
    """复数计算工具类"""


    @staticmethod

    def
 parse_complex(input_str):
        """解析复数字符串"""

        try
:
            return
 complex(input_str.replace(' ', ''))  # 去除空格
        except
 ValueError:
            raise
 ValueError(f"无法解析复数: {input_str}")

    @staticmethod

    def
 add(c1, c2):
        """复数加法"""

        return
 complex(c1.real + c2.real, c1.imag + c2.imag)

    @staticmethod

    def
 multiply(c1, c2):
        """复数乘法:(a+bi)(c+di) = (ac-bd) + (ad+bc)i"""

        real_part = c1.real * c2.real - c1.imag * c2.imag
        imag_part = c1.real * c2.imag + c1.imag * c2.real
        return
 complex(real_part, imag_part)

    @staticmethod

    def
 to_polar(complex_num):
        """转换为极坐标形式"""

        import
 math
        r = math.sqrt(complex_num.real**2 + complex_num.imag**2)
        theta = math.atan2(complex_num.imag, complex_num.real)
        return
 r, math.degrees(theta)

# 使用示例

calc = ComplexCalculator()

# 解析和计算

num1 = calc.parse_complex("3+4j")
num2 = calc.parse_complex("1-2j")

print
(f"加法结果: {calc.add(num1, num2)}")           # (4+2j)
print
(f"乘法结果: {calc.multiply(num1, num2)}")     # (11-2j)

# 极坐标表示

magnitude, angle = calc.to_polar(num1)
print
(f"极坐标: 模长={magnitude:.2f}, 角度={angle:.1f}°")

总结

通过今天的探索,我们发现这些"熟悉又陌生"的内置函数其实蕴含着强大的功能:

  1. 1. callable() - 动态调用的安全卫士
  2. 2. chr() - 字符编码的翻译官
  3. 3. @classmethod - 面向类的团队协作工具
  4. 4. compile() - 代码的动态编译器
  5. 5. complex() - 复数运算的基石

阅读推荐:

Python 内置函数系列:a开头函数

Python 内置函数系列:b开头系列函数


✨关注我,获取更多Python学习资源、实战项目和行业动态!在公众号后台回复"python学习",获取Python学习电子书籍!

最新文章

随机文章