Python classes - 在一行中调用多个 class 方法
Python classes - Call multiple class methods in one line
我正在尝试组合一些 class 方法或在其自身上应用初始值但没有成功。
class numOper:
def __init__(self, x):
self.x = x
def multiply(self, x):
self.x *= x
def add(self, x):
self.x += x
a = numOper(5)
print(a.x) # 5
a.multiply(3)
print(a.x) # 15
a.add(7)
print(a.x) # 22
a = numOper(5) # x = 5
a.multiply(3).add(7) # Error; trying multiply and then add to result
print(a.x)
a = numOper(5) # x = 5
a.multiply(a) # Error; trying to multiply by itself
这些导致
AttributeError: 'NoneType' object has no attribute 'multiply'
AttributeError: 'NoneType' object has no attribute 'add'
有什么办法可以做到这些吗?或调查?
在程序中 python,这似乎有效。
a = 5
def addf(a):
a += a
return a
addf(a)
或
a = 5
def addf(a):
a += a
return a
def double(a):
a *= 2
return a
double(addf(a))
multiply
和 add
没有明确地 return 任何东西,所以他们隐含地 return None
,因此你看到的错误。您可以改为显式 return self
以便您可以继续对其调用方法:
class numOper:
def __init__(self, x):
self.x = x
def multiply(self, x):
self.x *= x
return self # Here!
def add(self, x):
self.x += x
return self # And here!
我正在尝试组合一些 class 方法或在其自身上应用初始值但没有成功。
class numOper:
def __init__(self, x):
self.x = x
def multiply(self, x):
self.x *= x
def add(self, x):
self.x += x
a = numOper(5)
print(a.x) # 5
a.multiply(3)
print(a.x) # 15
a.add(7)
print(a.x) # 22
a = numOper(5) # x = 5
a.multiply(3).add(7) # Error; trying multiply and then add to result
print(a.x)
a = numOper(5) # x = 5
a.multiply(a) # Error; trying to multiply by itself
这些导致
AttributeError: 'NoneType' object has no attribute 'multiply'
AttributeError: 'NoneType' object has no attribute 'add'
有什么办法可以做到这些吗?或调查?
在程序中 python,这似乎有效。
a = 5
def addf(a):
a += a
return a
addf(a)
或
a = 5
def addf(a):
a += a
return a
def double(a):
a *= 2
return a
double(addf(a))
multiply
和 add
没有明确地 return 任何东西,所以他们隐含地 return None
,因此你看到的错误。您可以改为显式 return self
以便您可以继续对其调用方法:
class numOper:
def __init__(self, x):
self.x = x
def multiply(self, x):
self.x *= x
return self # Here!
def add(self, x):
self.x += x
return self # And here!