Python 使用多个参数从全局函数更新实例属性
我有一个全局函数,用于将类属性映射到类属性Python 使用多个参数从全局函数更新实例属性,python,Python,我有一个全局函数,用于将类属性映射到类属性 def f(x): return x**2 这个班是 class toy: def __init__(self,x): self.x=x @property def y(self): return f(self.x) 所以 给予 t、 x=2,t.y=4 如果我把t.x=3,我得到t.y=9。这是理想的行为。我的问题是: 对于多个参数的函数,正确的方法是什么 例如,如果 def g(
def f(x):
return x**2
这个班是
class toy:
def __init__(self,x):
self.x=x
@property
def y(self):
return f(self.x)
所以
给予
t、 x=2,t.y=4
如果我把t.x=3,我得到t.y=9。这是理想的行为。我的问题是:
对于多个参数的函数,正确的方法是什么
例如,如果
def g(x,a,b):
return a*x**2+b
控制属性y,并且a,b在类定义之外被修复,可以写入吗
class toy:
def __init__(self,x):
self.x=x
@property
def y(self):
return g(self.x,a,b)
还是有更好的方法?如何将全局变量传递到类实例的局部范围,以确定实例的属性 您可以使用
functools.partial
创建一个新的函数对象,其中某些参数已经传递给它:
import functools
def g(a, b, x):
return a*x**2+b
g1 = functools.partial(g, 32, 232) #placeholder values
class toy:
def __init__(self,x):
self.x=x
@property
def y(self):
return g1(self.x)
t = toy(100)
>>>t.y
>>>320232
但是,在类外声明a
和b
并将它们传递给属性中的g
是非常好的:
a = 100
b = 200
def g(x,a,b):
return a*x**2+b
class toy:
def __init__(self,x):
self.x=x
@property
def y(self):
return g(self.x, a, b)
最后,如果您在类中可能使用或不使用变量,请考虑将它们作为类属性实现:
class toy:
a = 100
b = 200
def __init__(self, x):
self.x = x
@property
def y(self):
return g(self.x, toy.a, toy.b)
您可以使用functools.partial
创建新的函数对象,其中某些参数已传递给它:
import functools
def g(a, b, x):
return a*x**2+b
g1 = functools.partial(g, 32, 232) #placeholder values
class toy:
def __init__(self,x):
self.x=x
@property
def y(self):
return g1(self.x)
t = toy(100)
>>>t.y
>>>320232
但是,在类外声明a
和b
并将它们传递给属性中的g
是非常好的:
a = 100
b = 200
def g(x,a,b):
return a*x**2+b
class toy:
def __init__(self,x):
self.x=x
@property
def y(self):
return g(self.x, a, b)
最后,如果您在类中可能使用或不使用变量,请考虑将它们作为类属性实现:
class toy:
a = 100
b = 200
def __init__(self, x):
self.x = x
@property
def y(self):
return g(self.x, toy.a, toy.b)
@kevinkayaks很乐意帮忙!还有一件事——如果我的类是在我要导入的模块中定义的呢。将函数链接回导入的模块的最佳实践是什么?@kevinkayaks我将反转导入,即将函数存储在模块中,导入函数,并使用\uuuuuuu main\uuu
中的类。但是,如果确实要导入该类,还可以将该函数存储在另一个模块中。这样就可以导入类,该类导入函数。如果有道理,请告诉我。谢谢你的帮助。这是有道理的。我可以制作一个函数模块并将其导入到类中module@kevinkayaks很乐意帮忙!还有一件事——如果我的类是在我要导入的模块中定义的呢。将函数链接回导入的模块的最佳实践是什么?@kevinkayaks我将反转导入,即将函数存储在模块中,导入函数,并使用\uuuuuuu main\uuu
中的类。但是,如果确实要导入该类,还可以将该函数存储在另一个模块中。这样就可以导入类,该类导入函数。如果有道理,请告诉我。谢谢你的帮助。这是有道理的。我可以制作一个函数模块并将其导入到类模块中