You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典定义时如何调用外部类方法传参设置键值

正确实现方案

你现有代码存在两个会直接报错的问题:

  1. at_on_in 被定义为实例方法,直接通过类名调用时缺少必填的self参数;方法内部直接写has_at/has_on无法找到对应类属性,且字符串拼接没加空格,会输出at themovies这类错误结果
  2. 字典字面量初始化时,不能直接引用同字典内还没定义完成的键,phrase求值时randomPlace这个名称根本不存在于当前作用域

第一步:修正类方法定义

这个方法不需要访问实例属性,直接加@staticmethod装饰器改成静态方法最合理,同时修复类属性引用和字符串拼接的问题:

class setPreposition:
    has_at = ['library', 'movies']
    has_on = ['table', 'train']

    @staticmethod
    def at_on_in(place):
        if place in setPreposition.has_at:
            return f'at the {place}'
        elif place in setPreposition.has_on:
            return f'on the {place}'
        return f'in the {place}'

第二步:正确构造字典

先拿到randomPlace的实际返回值,再传入类方法计算phrase的值即可:

# 先获取随机地点的返回值
random_place = myClss.getPlace
SAMPLE_DICT = {
    'randomPlace': random_place,
    'phrase': setPreposition.at_on_in(random_place),
    'key2': 'something else'
}

其他可选实现

  • 如果你用Python 3.8+,可以用海象运算符在字典内部完成赋值,不需要额外定义外部变量:
SAMPLE_DICT = {
    'randomPlace': (p := myClss.getPlace),
    'phrase': setPreposition.at_on_in(p),
    'key2': 'something else'
}
  • 如果你后续要给类加实例状态、必须保留实例方法定义,先实例化类再调用方法即可:
prep_tool = setPreposition()
random_place = myClss.getPlace
SAMPLE_DICT = {
    'randomPlace': random_place,
    'phrase': prep_tool.at_on_in(random_place),
    'key2': 'something else'
}

内容的提问来源于stack exchange,提问作者MLO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 18:36:51