简体   繁体   中英

How to call method without method name in python

class LinearRegression(nn.Module):
def __init__(self,input_size,output_size):
    # super function. It inherits from nn.Module and we can access everythink in nn.Module
    super(LinearRegression,self).__init__()
    # Linear function.
    self.linear = nn.Linear(input_dim,output_dim)

def forward(self,x):
    return self.linear(x)


input_dim = 1
output_dim = 1
model = LinearRegression(input_dim,output_dim)

In this code block when I want to call forward method in model object I can call 2 different ways

The first way

results = model.forward(car_price_tensor)

Second way

results = model(car_price_tensor)

And I try the second way on a different class and object it doesnt work. How it possible?

This behavior that lets you call a Python object like a function is enabled through a special method __call__ , some explanation here .

A torch.nn.Module is a class that implements this behavior. You class LinearRegression is a subclass of it so it inherits this behavior. By default the __call__ method is derived from your forward implementation but it not the same .

The difference in behavior is explained here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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