定义课堂外的信息
有没有办法在类中的 __init__ 部分定义一个值,将其发送到类外部的某个变量,而不调用类中的另一个函数?
就像
class c:
def __init__(self, a):
self.a = a
b = 4 # do something like this so that outside of class c,
# b is set to 4 automatically for the entire program
# when i use class c
def function(self):
... # whatever. this doesnt matter
我有多个类,它们的 b 值不同。我可以制作一个列表来告诉计算机更改 b,但我宁愿在每个类中设置 b
is there a way to define a value within a class in the __init__
part, send it to some variable outside of the class without calling another function within the class?
like
class c:
def __init__(self, a):
self.a = a
b = 4 # do something like this so that outside of class c,
# b is set to 4 automatically for the entire program
# when i use class c
def function(self):
... # whatever. this doesnt matter
i have multiple classes that have different values for b. i could just make a list that tells the computer to change b, but i would rather set b within each class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定我是否正确理解了这个问题,但尝试将此行添加到 __init__ 中:
我的意思是在分配给
b
之前。就像函数的第一行一样。I'm not sure I understood the question correctly, but try adding this line into the
__init__
:Before assignment to
b
I mean. Like the first line of the function.由于全局变量不好,请尝试使用类变量。 (有什么理由不能吗?)例如:
或者,更好的是:
global
,正如 doublep 所建议的,将绑定到模块的全局变量。由于它仅限于模块名称空间,因此这并不是一个糟糕的选择。Since globals are bad, try a class variable. (Is there any reason you can't?) For example:
or, better yet:
global
, as doublep suggests, will bind to a variable global to the module. Since it's limited to the module namespace, it's not that bad an option.基本上,答案是否定的。您可以创建一个为您执行回调的父类,然后除了将 b 值传递给父类构造函数之外,您不需要考虑它。但是除非您想使用全局变量(这不是一个好主意),否则无法从构造函数中返回不是对象的值。
Basically, the answer is no. You can make a parent class that does the callback for you, then you won't need to think about it beyond passing the b value to the parent class constructor. But unless you want to use global variables (which is not a good idea), there is no way to return a value from a constructor that is not the object.