【问题标题】:Python: How to determine the type of a property in a class?Python:如何确定类中属性的类型?
【发布时间】:2018-08-27 18:27:31
【问题描述】:

我定义了以下从其他一些类继承的类。 Goblin 是我从中扩展的 Python 依赖包。

class AnnotatedVertexProperty(goblin.VertexProperty):
    notes = goblin.Property(goblin.String)
    datetime = goblin.Property(DateTime)

class KeyProperty(goblin.Property):
    def __init__(self, data_type, *, db_name=None, default=None, db_name_factory=None):
        super().__init__(data_type, default=None, db_name=None, db_name_factory=None)

class TypedVertex(goblin.Vertex):
    def __init__(self):
        self.vertex_type = self.__class__.__name__.lower()
        super().__init__()

class TypedEdge(goblin.Edge):
    def __init__(self):
        self.edge_type = self.__class__.__name__.lower()
        super().__init__()

class Airport(TypedVertex):
    #label
    type = goblin.Property(goblin.String)
    airport_code = KeyProperty(goblin.String)
    airport_city = KeyProperty(goblin.String)
    airport_name = goblin.Property(goblin.String)
    airport_region = goblin.Property(goblin.String)
    airport_runways = goblin.Property(goblin.Integer)
    airport_longest_runway = goblin.Property(goblin.Integer)
    airport_elev = goblin.Property(goblin.Integer)
    airport_country = goblin.Property(goblin.String)
    airport_lat = goblin.Property(goblin.Float)
    airport_long = goblin.Property(goblin.Float)

在运行时,我需要迭代抛出的每个属性并能够确定其类类型(keyProperty 或 goblin.Property)我还需要能够确定值是字符串、整数等...

在实例化过程中,我创建了一个机场对象并将值设置如下:

lhr = Airport()
lhr.airport_code = 'LHR'
print (lhr.airport_code.__class__.mro())
lhr.airport_city = 'London'
lhr.airport_name = 'London Heathrow International Airport'
lhr.airport_region = 'UK-EN'
lhr.airport_runways = 3
lhr.airport_longest_runway = 12395
lhr.airport_elev = 1026
lhr.airport_country = 'UK'
lhr.airport_lat = 33.6366996765137
lhr.airport_long = -84.4281005859375 

但是,当我在调试对象时检查它时,我得到的只是属性名称,定义为字符串和值,定义为字符串、整数等...如何检查每个属性的对象类型? 有关如何处理此问题的任何帮助或建议?

【问题讨论】:

  • type内置函数怎么样:type(1) == int返回True,type(instance)返回类
  • 嗨,埃里克,我试过了。我可以在实例下的字典中获取所有属性,并使用字典中的键、值访问键(airport_code)和值(LHR)。但是,如果我尝试执行 type(key),它会将类型返回为 str。
  • 您能否提供一个最低限度的工作示例?定义一个简单的类并说明你的意思。
  • 如果goblin.Property 是一个描述符类型,那么就很难直接访问它。这是因为描述符可以改变 Python 在另一个对象中查找它的方式。我怀疑你的obj.__class__.__dict__ 方法是唯一真正的选择。

标签: python python-3.x multiple-inheritance


【解决方案1】:

我知道我在寻找什么。我必须调用 element.class.dict.items(): 并且我可以获得包含所有属性、映射等的字典...

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 2015-09-01
    • 2012-03-07
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多