python - 如何在对象名称之后使用括号?
问题描述
我想知道对象名称后面的括号。
我正在学习 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]
解决方案
在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 对象成为可调用对象的方法。
推荐阅读
- javascript - SPA 访问新页面时如何删除URL中的#?
- google-chrome-extension - 我正在开发 chrome 扩展,它将捕获下载文件并检查它是否为 PDF,然后在自定义 PDF 查看器中打开它
- sql-server - TSQL:基于 varchar 值的动态透视不能正常工作
- apache-arrow - 如何根据箭头::StringArray 的内部数据构建一个arrow::LargeStringArray?
- css - HTML_CSS_Media_query_not_working
- regex - Viatra 检查文本是否与正则表达式匹配不适用于参数
- google-cloud-platform - Terraform 多级地图
- class-validator - 我想在每个属性上同时使用装饰器 @Transform 和 @Type
- html - 使用角度上传带有base64的图像时,假路径存储在mongodb中
- python - 除了变量字符,如何用“-”替换字符串中的每个字母?(Python)