如何更改模块中类的变量?

时间:2017-01-17 11:30:12

标签: python python-3.x

如何将some_module.Var.b的值更改为Numbers.a的值

主要代码:

class Var:
    b = 0

some_module:

>>> some_module.Var.b = 2
>>> Number.Var.a = 2

通缉输出:

>>> some_module.Var.b = 0
>>> Number.Var.a = 0

实际输出:

assert b>0 : "Invalid Assertion, b must be positive"

2 个答案:

答案 0 :(得分:0)

如果不再继续下去,我认为您所遇到的错误就是

class Variabler:
    a = 0
    b = 0
    c = 0

a,b和c是类变量。对于您实例化的任何类,这些都是相同的。这可能会导致意想不到的后果。

你想要的是__init__方法,

class Variabler:
    def __init__(self):
        a = 0
        b = 0
        c = 0

现在您实例化此类的实例:

var_name = Variabler()

您可以根据需要更改或访问此变量,而无需修改任何其他实例。

other_var = Variabler()
other_var.a = 100
>>> var_name.a
>>> 0

您可能根本不想在程序中使用类变量。您可以在python documentation here

了解有关课程的更多信息

答案 1 :(得分:-1)

Number.a = some_module.Var.b更改为some_module.Var.b = Numbers.a

import some_module

class Number:

    a = 2

some_module.Var.b = Number.a
print("some_module.Var.b =", some_module.Var.b)
print("Number.a =", Numbers.a)

输出:

>>> some_module.Var.b = 2
>>> Number.a = 2
相关问题