2014-12-06 65 views
1

访问一个枚举如何从另一个类访问枚举 - 例如B类如下:在Python

from examples import A 

class B: 
    properties = A 

    def __init__(self, name, area, properties): 
     self.name = name 
     self.area = area 
     self.properties = properties 

B.property = B("test", 142.43, A) 
print ("B color: "+B.properties.color) 
print ("A color: "+str(A.color._value_)) 

#in separate module 
from enum import Enum 

class A(Enum): 
    color = "Red" 
    opacity = 0.5 

print("A color: "+str(A.color._value_)) 

当我运行A级:

A color: Red 

当我运行B类:

print ("B color: "+B.properties.color) 
AttributeError: 'module' object has no attribute 'color' 
+0

是类'B'的'__init__'部分? – 2014-12-06 11:10:53

+0

那么包含'A' *的模块名为*?也许你把它命名为'A.py'? – 2014-12-06 11:15:56

回答

3

A模块包含您的类,而不是TH e类本身。你必须引用模块仍处于类:

from examples.A import A 

或使用

properties = A.A 

print ("A color: "+str(A.A.color._value_)) 

尽量避免使用大写名称的模块; Python style guide (PEP 8)建议您使用所有小写字母作为模块名称。这样你就不会轻易混淆模块和其中包含的类。