从另一个类打印属性

时间:2014-09-14 09:14:36

标签: python class

说我有这段代码:

class Foo:
    def __init__(self, name):
        self.name = name

class Other:
    def __init__(self):
        str = input("Type a, b, c, or d: ")
        print(str.name)

a = Foo('apple')
b = Foo('bear')
c = Foo('chicken')
d = Foo('duck')

显然,这个程序不起作用,因为str是字符串而不是实例。 有没有办法使用name类中的代码从Foo类的实例中打印属性Other? 或者使用Foo类中的代码是唯一的方法吗?

2 个答案:

答案 0 :(得分:2)

您尝试使用名称访问全局变量。您可以使用globals获取将全局变量名称映射到对象的字典:

class Foo:
    def __init__(self, name):
        self.name = name

class Other:
    def __init__(self):
        v = input("Type a, b, c, or d: ")
        print(globals()[v].name)

a = Foo('apple')
b = Foo('bear')
c = Foo('chicken')
d = Foo('duck')

Other()

<强>更新

使用globals表示设计不佳。

您最好使用序列或映射来存储多个对象。

class Foo:
    def __init__(self, name):
        self.name = name

class Other:
    def __init__(self, mapping):
        v = input("Type a, b, c, or d: ")
        print(mapping[v].name)

foo_list = [Foo('apple'), Foo('bear'), Foo('chicken'), Foo('duck')]
mapping = {foo.name[0]: foo for foo in foo_list}  # dict comprehension
Other(mapping)

答案 1 :(得分:0)

解决此问题的实际方法是使用Other类创建Foo个对象,然后将这些Foo对象保留为Other类的属性。

摆弄globals()可能会做你想要的,但它并没有解决设计中更大的问题:

class Foo:
   def __init__(self, name):
      self.name = name

class Other:
   def __init__(self):
      self.foos = {'a': Foo('apple'), 'b': Foo('bear'),
                   'c': Foo('chicken'), 'd': Foo('duck')}

   def ask(self):
      i = input('Please enter a,b,c or d: ')
      obj = self.foos.get(i)
      if obj:
         print('You selected {0.name}'.format(obj))
      else:
         print('Sorry, {} is not a valid choice'.format(i))

z = Other()
z.ask()
相关问题