如何获取类中具有函数的对象



我有一个数据库类,它将对象存储在数据库中.py:

class Database(dict):
def get_objects_by_object_type(self, object_type):
# get a list of objects based on object type

db = Database()

然后我在models.py中有这两个类:

class IdentifiableObject(object):
def __init__(self, object_id):
self.object_id = object_id
self.object_type = self.__class__.__name__.lower()
@classmethod
def get_object_type(cls):
return f"{cls.__name__.lower()}"

class Ingredient(IdentifiableObject):
def __init__(self, object_id, unsuitable_diets=[]):
super(Ingredient, self).__init__(object_id=object_id)
self.unsuitable_diets = unsuitable_diets

如何按类型获取对象:例如,如果我传递一个类型为component的对象,它应该得到所有的成分并返回它。

# Ingredient.get_object_type() is equal to 'ingredient'

ingredients = db.get_objects_by_object_type(object_type=Ingredient.get_object_type())

我认为这个片段对您有用。如果我误解了你的问题,请留下评论。

class IdentifiableObject(object):
def __init__(self, object_id):
self.object_id = object_id
self.object_type = self.__class__.__name__.lower()
@classmethod
def get_object_type(cls):
return f"{cls.__name__.lower()}"

class Ingredient(IdentifiableObject):
def __init__(self, object_id, unsuitable_diets):  # don't use mutable value as default argument value.
super(Ingredient, self).__init__(object_id=object_id)
if unsuitable_diets is None:
unsuitable_diets = []
self.unsuitable_diets = unsuitable_diets

class Database(dict):
def get_objects_by_object_type(self, object_type):
return [values for values in self.values() if values.get_object_type() == object_type]

if __name__ == '__main__':
db = Database({
"1": IdentifiableObject(1),
"2": Ingredient(2),
"3": Ingredient(3),
})
ingredients = db.get_objects_by_object_type(Ingredient.get_object_type())
identifiable_objects = db.get_objects_by_object_type(IdentifiableObject.get_object_type())
print(ingredients)
print(identifiable_objects)

输出:

[<__main__.Ingredient object at 0x10a933880>, <__main__.Ingredient object at 0x10a933820>]
[<__main__.IdentifiableObject object at 0x10a9338e0>]

这是一种按类型识别对象的方法:

class MyClass:
pass
some_objects = [5, "string", MyClass()]
for o in some_objects:
if type(o) == MyClass:
print("Found item of MyClass")

相关内容

  • 没有找到相关文章

最新更新