python中函数指针的替换

2024-04-24 10:15:39 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

在python中,函数是一级数据类型。

def z(a):
    print(a)
def x(a):
    print "hi"

functions = [z,x]
y = functions[0]
y("ok") # prints "ok"
y = functions[1]
y("ok") # prints "hi"

Python支持函数作为一级数据类型。所以你可以这样做:

def foo(x):
    print("foo: " + x)

def bar(x):
    print("bar: " + x)

f = foo
f("one")
f = bar
f("ten")

印刷品

foo: one
bar: ten

这与您在C中使用函数指针的经验非常相似。虽然Python当然支持更精细的面向对象编程风格,但是您没有义务使用它们。

使用类的示例,其中可以将相关函数分组在一起:

class Dog:
    def noise(self, x):
        print("bark! " + x)
    def sleep(self):
        print("sleeping on floor")

class Cat:
    def noise(self, x):
        print("meow! " + x)
    def sleep(self):
        print("sleeping on keyboard")

a = Dog()
a.noise("hungry")
a.sleep()

a = Cat()
a.noise("hungry")
a.sleep()

此版本打印:

bark! hungry
sleeping on floor
meow! hungry
sleeping on keyboard

你可以简单地把函数放在一个dict中

{"type1": function1,
 "type2": function2,
 "type3": function3,
}.get(config_option, defaultfunction)(parameters, go, here)

如果没有匹配的键,则调用default_function

如果你愿意,你可以把选择和电话分开

selected_function = {"type1": function1,
                     "type2": function2,
                     "type3": function3,
                     }.get(config_option, defaultfunction)

some_instance = SomeClass(selected_function)

相关问题 更多 >