在python中调用在另一个类中声明的类

时间:2017-11-29 12:32:54

标签: python

我是学习python的。我想知道如何在另一个类中使用类来执行类似的操作:

class wardrove:
    class drawer1:
        def __init__(self):
            self.sokcs='red'
    class drawer2:
        def __init__(self):
            self.hats='black'

    def __init__(self):
        self.drawer1()
        self.drawer2()
        self.shirts='white'

wardrove_lane=[]
for i in range(0,2):
    wardrove_lane.append(wardrove())


wardrove_lane[1].drawer1.sokcs='green'
wardrove_lane[0].drawer1.sokcs='blue'

print(wardrove_lane[1].drawer1.sokcs)
print(wardrove_lane[0].drawer1.sokcs)  

在这个例子中我得到:

  

蓝色

     

蓝色

但我希望:

  

绿色

     

蓝色

由于

2 个答案:

答案 0 :(得分:0)

您需要将self.drawer1()self.drawer2()分配给不同的实例,例如self.d1self.d2

class wardrove:
   def __init__(self):
       self.d1 = self.drawer1()
       self.d2 = self.drawer2()
       self.shirts='white'
   class drawer1:
      def __init__(self):
         self.sokcs='red'
   class drawer2:
      def __init__(self):
         self.hats='black'


wardrove_lane=[]
for i in range(0,2):
   wardrove_lane.append(wardrove())


wardrove_lane[1].d1.sokcs='green'
wardrove_lane[0].d2.sokcs='blue'
print(wardrove_lane[1].d1.sokcs)
print(wardrove_lane[0].d2.sokcs)

输出:

green
blue

但是,如果您确实希望按类实例访问属性,那么您可以使用classmethod包装器稍微重构代码:

class wardrove:
   def __init__(self):
       self.d1 = self.drawer1()
       self.d2 = self.drawer2()
       self.shirts='white'
   class drawer1:
      sokcs='red'
      @classmethod
      def update(cls, value):
          cls.sokcs = value
   class drawer2:
      hats='black'
      @classmethod
      def update(cls, value):
         cls.hats = value

wardrove_lane=[]
for i in range(0,2):
   wardrove_lane.append(wardrove())

wardrove_lane[1].drawer1.update('green')
wardrove_lane[0].drawer2.update('blue')

答案 1 :(得分:0)

您需要以两种方式在两个新变量中实例化构造函数:

class wardrove:
   class drawer1:
       def __init__(self):
           self.sokcs='red'
   class drawer2:
       def __init__(self):
           self.hats='black'

   def __init__(self):
       self.d1 = self.drawer1()
       self.d2 = self.drawer2()
       self.shirts='white'

wardrove_lane=[]
for i in range(0,2):
    wardrove_lane.append(wardrove())


wardrove_lane[1].d1.sokcs='green'
wardrove_lane[0].d1.sokcs='blue'

print(wardrove_lane[1].d1.sokcs)
print(wardrove_lane[0].d1.sokcs)