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

2024-09-30 22:16:20 发布

您现在位置: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列表,并检查字符串中是否包含它们中的任何一个。你知道吗

做这个或其他数据结构的最佳方法是什么?你知道吗

(抱歉,如果你不喜欢化学,我只是想让复习更有趣)


Tags: 实例方法字符串属性initdefclassol
1条回答
网友
1楼 · 发布于 2024-09-30 22:16:20

我不确定这是否是最干净的方法,我删除了实例变量,并在每个类中创建了一个常量列表。这样比较容易引用,而且列表似乎是一个常量:

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

相关问题 更多 >