首页 > 解决方案 > 如何在对象名称之后使用括号?

问题描述

我想知道对象名称后面的括号。

我正在学习 AI 并构建 AI 模型,现在在教程的代码中,作者写了一行,其中包含对象名称后面的括号:self.model(...)

其中 self.model 是 Network 类的对象。对象如何将括号作为对象而不是函数?现在我想知道对象名称后面的括号。

class Network(nn.Module):

    def __init__(self, input_size, nb_action):
        super(Network, self).__init__()
        self.input_size = input_size
        self.nb_action = nb_action
        self.fc1 = nn.Linear(input_size, 30)
        self.fc2 = nn.Linear(30, nb_action)

    def forward(self, state):
        x = F.relu(self.fc1(state))
        q_values = self.fc2(x)
        return q_values

class Dqn():

    def __init__(self, input_size, nb_action, gamma):
        self.gamma = gamma
        self.reward_window = []
        self.model = Network(input_size, nb_action)
        self.memory = ReplayMemory(100000)
        self.optimizer = optim.Adam(self.model.parameters(), lr = 0.001)
        self.last_state = torch.Tensor(input_size).unsqueeze(0)
        self.last_action = 0
        self.last_reward = 0

    def select_action(self, state):
        probs = F.softmax(self.model(Variable(state, volatile = True))*100) # <-- The problem is here where the self.model object is CALLED with Parenthesis.
        action = probs.multinomial(10)
        return action.data[0,0]

标签: pythonartificial-intelligencepytorch

解决方案


在python中,一切都是对象。您创建和调用的函数也是对象。python 中可以调用的任何东西都是可调用对象

但是,如果您希望python中的类对象是可调用对象,则__call__必须在类内部定义该方法。

当对象被调用时,__call__(self, ...)方法被调用。

这是一个例子。

class Foo:
    def __init__(self, x=0):
        self.x = x

    def __str__(self):
        return f'{self.__class__.__name__}({self.x})'

    def __call__(self, *args):
        print(f'{self} has been called with {args} as arguments')


f1 = Foo(5)
f2 = Foo()

f1()  # f1.__call__()
f2()  # f2.__call__()
f1(1, 2, 3)  # f1.__call__(1, 2, 3)
f2(10, 20)  # f2.__call__(10, 20)

输出:

Foo(5) has been called with () as arguments
Foo(0) has been called with () as arguments
Foo(5) has been called with (1, 2, 3) as arguments
Foo(0) has been called with (10, 20) as arguments

这就是如何使 python 对象成为可调用对象的方法。


推荐阅读