[英]OOP: Object parameter depending on the place where I call a method
This is not a purely technical issue, I am trying to find the cleanest and most efficient solution possible.这不是一个纯粹的技术问题,我试图找到最干净、最有效的解决方案。
I am doing a tree exploration program in Python 3, and I use an object I need in each leaf of this tree.我正在用 Python 3 做一个树探索程序,我在这棵树的每一片叶子中使用了一个我需要的对象。 I want the values of the parameters of my object to be editable at different places in my program (in the different leaves), and the value to be updated in all the leaves, so I need to use the same object everywhere (pointers to the same object and not copies of the object).我希望我的对象的参数值可以在我的程序的不同位置(在不同的叶子中)进行编辑,并且在所有叶子中更新该值,所以我需要在任何地方使用相同的对象(指向相同的对象而不是对象的副本)。 However, I would like one of the parameters to depend on the leaf in which the object is located.但是,我希望参数之一取决于对象所在的叶子。
I actually need many objects like that.我实际上需要很多这样的对象。
So I see several options:所以我看到了几个选项:
I have never been faced to such a situation, so would like to have your opinion on these options or a better idea to write a code as clean and efficient as possible.我从来没有遇到过这种情况,所以想了解您对这些选项的看法,或者有更好的想法来编写尽可能干净和高效的代码。 Thanks for your help!谢谢你的帮助!
PS: I have about a thousand leaves and a hundred objects per leaf. PS:我有大约一千片叶子和每片叶子一百个物体。
Currently working on option 1, still not sure if it's the best one.目前正在研究选项 1,仍然不确定它是否是最好的。
Not super sure what you're asking.不太确定你在问什么。 However, maybe class variables can solve your problem.但是,也许类变量可以解决您的问题。 Each Leaf
has certain instance variables, that are specific/unique to each leaf instance.每个Leaf
都有特定的实例变量,这些变量对于每个叶子实例都是特定的/唯一的。 The Leaf
class has a class variable which is shared among all leaf instances. Leaf
类有一个在所有叶子实例之间共享的类变量。
class Leaf:
class_variable = 0
def __init__(self):
from random import randint
Leaf.class_variable = randint(0, 100)
self.instance_variable = randint(0, 100)
number_of_leaves = 5
leaves = [Leaf() for _ in range(number_of_leaves)]
for leaf in leaves:
print(f"class variable: {leaf.class_variable}\ninstance variable: {leaf.instance_variable}")
Output:输出:
class variable: 79
instance variable: 7
class variable: 79
instance variable: 57
class variable: 79
instance variable: 93
class variable: 79
instance variable: 2
class variable: 79
instance variable: 65
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.