找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 5804|回复: 0

[其它] Ren'Py中使用反射(reflection),根据字符串执行模块或类的方法

[复制链接]
发表于 2021-3-1 11:19:25 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
翻到了龙氏的一个老帖子,提到使用变量名执行方法或函数的思路。原帖如下:
将变量值做为函数名并调用对应函数

做一点补充,python内置的eval函数只能执行一个“表达式(expression)”,通常只拿来做一些数学运算或者字符串处理。

更全面的方法应该是使用反射(reflection)技术,通过字符串调用模块或类的方法。
下面是一个样例:

[RenPy] 纯文本查看 复制代码
init python:
    class Calculator:
        def add(self, a, b):
            return a+b
        def sub(self, a, b):
            return a-b;
        def multiply(self, a, b):
            return a*b;
        def devide(self, a, b):
            # 这里除法结果将返回整形,可以根据需要修改返回类型和精度
            return a/b

    calculator = Calculator()

    def calc(a, b, operator):
        # 判断对象中是否包含名为“operator”的方法。
        # 注意 operator 入参是字符串
        if(hasattr(calculator, operator)):
            # 反射技术的核心函数
            func = getattr(calculator, operator)
            store.result = str(func(a, b))
        else:
            store.result = ""

define a = 3
define b = 2
define operator = ""
default result = ""

screen test():

    text "变量a:[a]" xpos 0.4 ypos 0.3
    text "变量b:[b]" xpos 0.6 ypos 0.3
    text "计算结果:[result]" xpos 0.5 ypos 0.5

    hbox:
        xpos 0.5
        ypos 0.7

        textbutton _("相加") action Function(calc, a, b, "add")
        textbutton _("相减") action Function(calc, a, b, "sub")
        textbutton _("相乘") action Function(calc, a, b, "multiply")
        textbutton _("相除") action Function(calc, a, b, "devide")

label main_menu:
    return

define e = Character("艾琳")

label start:


    call screen test


样例中为了看起来直观,把参与运算的两个参数和反射的方法名写死了。实际使用的时候可以定义变量后使用。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|RenPy中文空间 ( 苏ICP备17067825号|苏公网安备 32092302000068号 )

GMT+8, 2024-3-28 18:04 , Processed in 0.131894 second(s), 14 queries , File On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表