如何按Python中类的属性排序?

时间:2018-10-25 20:00:42

标签: python

我设置了两个类(具有一些不相关的其他属性)。

class Alcohol():
    def __init__(FunctionalGroup):
        FunctionalGroup.Naming = ["hydroxy", "ol"]

class Halogenoalkane():
    def __init__(FunctionalGroup):
        FunctionalGroup.Naming = ["chloro", "bromo", "iodo"]

我希望能够将给定的字符串(例如ethanol2-chloromethane)排序为其中之一,并根据名称适合的类创建一个实例。例如:

>>> Name: Ethanol
This is an alcohol.

我正在寻找一种方法来遍历每个类中的FunctionalGroup.Naming列表,并检查字符串中是否包含它们。

执行此操作或替代数据结构的最佳方法是什么?

(对不起,如果您不喜欢化学,我只是想让它变得更有趣)

1 个答案:

答案 0 :(得分:3)

我不确定这是否是最干净的方法,因此我删除了实例变量,而是在每个类中创建了一个常量列表。这样一来,引用起来就更容易了,无论如何列表似乎都是常量:

class Alcohol():
    Naming = ["hydroxy", "ol"]

    def __init__(self):
        print ' ---> Alcohol'

class Halogenoalkane():
    Naming = ["chloro", "bromo", "iodo"]

    def __init__(self):
        print ' ----> Halogen'

str = 'hydroxy'
classes = [Alcohol, Halogenoalkane]

chosen_class = object
for cl in classes:
    if str in cl.Naming:
        chosen_class = cl

print '{} is an:'.format(str)

obj = chosen_class()  # instantiate the class

输出:

hydroxy is an:
 ---> Alcohol