仅更改 Python 类中一个对象的 self 属性
我陷入了Python中的一个问题......(我是一个绝对的初学者,但我需要做一些 环境科学模型..) 所以问题是我有:
class C:
def __init__(self, x, y, z):
self.x = x
self.y = self.x * 8
self.z = self.y * 9 + 0.5
self.w = self.z +2
one = C(5,8,12)
two = C(2,12,12)
three = C(1,2,3)
所以...我想更改 self.z 但仅限于对象三 (我希望它是 self.z = 12 * self.x );
我必须在 self.w 中调用它,所以我无法在我的实例之后修改它......
你对初学者有什么建议吗? 非常感谢您,祝您有愉快的一天!
I'm stuck on a problem in Python... (i'm an absolute beginner but i need to do a little
environmental science model..)
so the problem is I have:
class C:
def __init__(self, x, y, z):
self.x = x
self.y = self.x * 8
self.z = self.y * 9 + 0.5
self.w = self.z +2
one = C(5,8,12)
two = C(2,12,12)
three = C(1,2,3)
So... i want to change the self.z but only for the object three
(i want it to be self.z = 12 * self.x );
I have to call it in self.w so i can't modify it after my istances...
do you have any suggestion to a beginner?
Thank you so much and have a nice day!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一些笔记。首先,您实际上并没有使用在
__init__(self, x, y, z)
中传递的y
或z
参数。为了允许动态重载,您可能需要将各个分配分解为它们自己的方法,以便更容易更改您想要的行为。
您可以在下面传入一个自定义函数,该函数将在计算
z
时应用于x
值。使用它:
A few notes. First you are not actually using the arguments of
y
orz
that are passed in__init__(self, x, y, z)
.To allow on the fly overloading, you may want to break out the individual assignments into their own methods so it is easier to change the behavior you want.
Below you can pass in a custom function that will be applied to the
x
value when calculatingz
.to use it: