我一直以为我看的代码有语法错误,直到我刚刚才发现他的玄机
先上代码:
import torch.nn as nn
class A():#nn.Module
def __init__(self,a="MaXh",b=100):
super(A, self).__init__()
self.name = a
self.age = b
def forward(self,name2):
print(f"Hello, I'm{self.name} and i am {self.age} yearsold","\n","my girlfriend is",name2)
return name2
class B:
def __init__(self,c=0):
self.a = A()
def forward(self,name2):
out=self.a(name2)#看似有语法错误,不应该是out=self.a.forward(name2) ?
return out
b = B()
b.forward("ma")
运行结果:报错
但是,如果让A类继承nn.Module:
import torch.nn as nn
class A(nn.Module):#
def __init__(self,a="MaXh",b=100):
super(A, self).__init__()
self.name = a
self.age = b
def forward(self,name2):
print(f"Hello, I'm{self.name} and i am {self.age} yearsold","\n","my girlfriend is",name2)
return name2
class B:
def __init__(self,c=0):
self.a = A()
def forward(self,name2):
out=self.a(name2)#看似有语法错误,不应该是out=self.a.forward(name2) ?
return out
b = B()
b.forward("ma")
代码中看似有语法错误的那一行就能正常运行:
Hello, I'mMaXh and i am 100 yearsold
my girlfriend is ma
'ma'
Why?