[英]Should I use a class to define functions that will use the same arguments, or should I use global variables?
First of all, apologies if the question has already been answered somewhere, I have not managed to find an answer to my question, but I am fairly new to the use of stackoverflow. 首先,如果问题已在某个地方得到解答,我道歉,我没有设法找到我的问题的答案,但我对使用stackoverflow相当新。
I am trying to optimize some code, and I would like to do it the "right" way. 我正在尝试优化一些代码,我想以“正确”的方式做到这一点。 I have a function A that does pre-processing and defines some variables that will be used by another function B. Now, I cannot define those variables directly in B because I want to avoid repeating the processing step.
我有一个函数A进行预处理并定义了一些将由另一个函数B使用的变量。现在,我无法直接在B中定义这些变量,因为我想避免重复处理步骤。 I could pass on the variables as arguments to the function B, but to simplify this I would like to avoid this.
我可以将变量作为参数传递给函数B,但为了简化这一点,我想避免这种情况。
One option would of course be to use global variables, but I read in multiple places that this is a bad habit, one of the reason being that it breaks encapsulation. 一种选择当然是使用全局变量,但我在多个地方读到这是一个坏习惯,其中一个原因是它破坏了封装。
An alternative that I could see would be to define a class (some sort of a master class) in which I put all the functions to use and pass the "self" for accessing the variables. 我可以看到的另一种方法是定义一个类(某种类的主类),我在其中放置所有要使用的函数并传递“self”来访问变量。 Does anyone have some arguments against this?
有没有人反对这个? Is this also a bad approach for some reason?
出于某种原因,这也是一种糟糕的方法吗?
Thank you in advance to anyone who has some element of response ! 提前感谢任何有回应要素的人!
Using self
is the best approach. 使用
self
是最好的方法。 I guess your case is something similar to this. 我想你的情况类似于此。
class DemoClass:
def __init__(self, name, age):
self.name = name
self.age = age
def fun1(self):
print(self.name)
def fun2(self):
print(self.age)
Here you can access the variables as self (instance of class) is passed. 在这里,您可以在传递self(类的实例)时访问变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.