有没有办法从另一个函数访问在一个函数中创建的类的属性?

时间:2016-08-24 06:09:14

标签: python python-2.7 function global

有没有办法从另一个函数访问在一个函数中创建的类的属性?

class Component(object):
    Name = ''
    Num = 100

    def __setattr__(self, name, value):
        object.__setattr__(self, name, value)

def one():
    exec('AAA' + '=Component()')
    AAA.Name = 'AAA'
    AAA.Num = AAA.Num * 2
    print '1', AAA.Name, AAA.Num

def two():
    print '2', AAA.Name, AAA.Num

one()
two()

我收到“NameError:全局名称'AAA'未定义”

3 个答案:

答案 0 :(得分:0)

类级别属性属于该类,因此在该类的所有实例之间共享。

如果您希望类的不同实例具有不同的namenum属性(顺便说一下,您应该为实例使用小写的属性名称),则应将它们添加为实例属性。您可以使用类名访问类属性(例如Component.NUM)。

class Component(object):
    NAME = ''
    NUM = 100

    def __init__(self, name, num):
        self.name = name
        self.num = num

print Component.NAME  # ''
print Component.NUM  # 100

c = Component('AAA', Component.NUM * 2)
print c.name  # 'AAA'
print c.num  # 200

答案 1 :(得分:0)

一种可能的解决方案:

创建一个全局列表(tuple,dict或任何你想要的正确数据结构)并将实例添加到第一个函数的列表中,然后从函数二中的列表中获取实例。

但是,不建议使用全局变量。

答案 2 :(得分:0)

class之外实例化function并在函数中使用该类实例。以下是代码:

>>> class Component(object):
...     Name = ''
...     Num = 100
...     def __setattr__(self, name, value):
...         object.__setattr__(self, name, value)
...
>>> # Moved object creation to outside of func
... exec('AAA' + '=Component()')
>>>
>>> def one():
...     AAA.Name = 'AAA'
...     AAA.Num = AAA.Num * 2
...     print '1', AAA.Name, AAA.Num
...
>>> def two():
...     print '2', AAA.Name, AAA.Num
...     AAA.Name = 'BBB'
...     AAA.Num = AAA.Num * 2
...     print '3', AAA.Name, AAA.Num
...
>>> one()
1 AAA 200
>>> two()
2 AAA 200
3 BBB 400
相关问题