Python 内Class 赋值

Python Inner Class value assignment

我在 class 中创建了一个内部 class 并创建了 class 的两个实例,但是当为内部 class 属性分配不同的值时,它是分配给两个实例。谁能帮忙? 这是代码

class cl1:
    def __init__(self,tagName):
        self.name = tagName
    name1 = 'tagName'
    class cl2:
        name2 = 'name2'

test1 = cl1('test1')
test2 = cl1('test2')
test1.cl2.name2 = "cl1"
test2.cl2.name2 = 'cl2'
print (test1.cl2.name2)

当运行它时,结果是

cl2

为什么不是分配的“cl1”?

价值:

test1.cl2.name2

是 class cl2 的 class 属性。它与那个 class 相关联,而不是那个 class 的实例。因此,即使您正在通过对 cl1 class 的实例的引用来设置该属性的值,但由于只有其中一个,所以您将其设置为的最后一项将获胜。您的 print 语句正在打印相同的单个值。

Google “python class vs 实例变量” 一些关于 class 和实例 [=32 之间的区别的好看的文章=].

这是一个示例,1) 提供实例与 class 属性,就在您想要它们的地方,以及 2) 重命名所涉及的 classes 以具有大写名称,因此当您重新引用实例属性与 class 属性。

class Cl1:
    class Cl2:
        def __init__(self, tagName):
            self.name2 = tagName

    def __init__(self, tagName1, tagName2):
        self.name1 = tagName1
        self.cl2 = Cl1.Cl2(tagName2)

test1 = Cl1('test1', 'test2')
test2 = Cl1('test2', 'test2')
test1.cl2.name2 = 'cl1'
test2.cl2.name2 = 'cl2'
print(test1.cl2.name2)

结果:

cl1

请注意,因为您希望内部 class 的实例与外部 class 的每个实例相关联,所以内部 class 的构造函数必须实例化一个实例内部 class 作为创建外部 class 实例的一部分。

另请注意对 self 的引用。实例变量是在 classes 的构造函数(它的 __init__ 函数)中创建的,方法是在 self 上引用它们,这是对正在创建的实例的引用。