定义课堂外的信息

发布于 2024-08-31 12:56:53 字数 508 浏览 10 评论 0原文

有没有办法在类中的 __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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无言温柔 2024-09-07 12:56:53

我不确定我是否正确理解了这个问题,但尝试将此行添加到 __init__ 中:

global b

我的意思是在分配给 b 之前。就像函数的第一行一样。

I'm not sure I understood the question correctly, but try adding this line into the __init__:

global b

Before assignment to b I mean. Like the first line of the function.

相思故 2024-09-07 12:56:53

由于全局变量不好,请尝试使用类变量。 (有什么理由不能吗?)例如:

class C(object):
    def __init__(self,a):
        self.a=a
        C.b=4

或者,更好的是:

class C(object):
    b=4
    def __init__(self,a):
        self.a=a

global,正如 doublep 所建议的,将绑定到模块的全局变量。由于它仅限于模块名称空间,因此这并不是一个糟糕的选择。

Since globals are bad, try a class variable. (Is there any reason you can't?) For example:

class C(object):
    def __init__(self,a):
        self.a=a
        C.b=4

or, better yet:

class C(object):
    b=4
    def __init__(self,a):
        self.a=a

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.

柠檬 2024-09-07 12:56:53

基本上,答案是否定的。您可以创建一个为您执行回调的父类,然后除了将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文