繁体   English   中英

Python class __call__ 方法和点符号

[英]Python class __call__ method and dot notation

我的目标是使用 SimpleNamespace 模块对字典中的 select 字符串使用点符号,同时能够更改要使用的字典。

为此,我尝试修改 class __call__方法以根据先前设置的变量更改 output。 但是,由于使用了__call__方法,它需要使用()来包含它,这打破了点符号的简单格式。 此外,我还需要能够使用 class 方法来更改我正在寻找的选项。

class i: x, y = 1, 2
class j: x, y = 3, 4
class myClass:
    def __init__(self):
        self.a, self.b = i(), j()
        self.selection = "a"
    def set_selection(self, selection):
        self.selection = selection
    def __call__(self):
        return getattr(self, self.selection)

mc = myClass()
print(mc().x) ## this generates the output i am wanting by using the __call__ method
mc.set_selection("b") ## i still need to call class methods
print(mc().x)
print(mc.x) ## this is the syntax i am trying to achive

尽管mc().x有效,但它不是点符号。

我在此示例中寻找的 output 类似于:

import myClass
data = myCalss()

print(data.x + data.y) 
#>>> 3
data.set_selection("b")
print(data.x + data.y) 
#>>> 7

似乎__call__()是您想要的接口的错误选择。 相反,也许__getattr__()是你想要的:

class i: x, y = 1, 2
class j: x, y = 3, 4
    
class myClass:
    def __init__(self):
        self.a, self.b = i(), j()
        self.selection = "a"
        
    def set_selection(self, selection):
        self.selection = selection
        
    def __getattr__(self, at):
        return getattr(getattr(self, self.selection), at)

data = myClass()

print(data.x + data.y)
# 3
data.set_selection("b")
print(data.x + data.y) 
# 7

可能需要进行一些检查以确保选择有效。

此外,如果您将更深入地探索此类内容,可能值得阅读描述符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM