簡體   English   中英

如何在一個 class 中實例化類並將其用作接口

[英]How to instantiate classes in one class and use it as interface

在一個 class 中實例化所有類並將其用作將激活這些實例的方法的接口的更有效方法是什么? 我應該使用抽象還是“abc”package?

例如:

class A:
    def __init__(self):
        self.match = "number"
        self.num = 10

    def shoot(self):
        return self.num

class B:
    def __init__(self):
        self.match = "number"
        self.num = 20

    def shoot(self):
        return self.num

class C:
    def __init__(self):
        self.match = "word"
        self.word = "Some beautiful word"

    def shoot(self):
        return self.word


class AllClasses:
    def __init__(self):
        self.a = A()
        self.b = B()
        self.c = C()
        self.all_instances = [
            instance
            for name, instance in vars(self).items()
        ]

    def shoot_numbers(self):
        for instance in self.all_instances:
            if hasattr(instance, "match") and instance.match == "number":
                print(instance.shoot())

    def shoot_words(self):
        for instance in self.all_instances:
            if hasattr(instance, "match") and instance.match == "word":
                print(instance.shoot())


inst = AllClasses()
inst.shoot_numbers()
inst.shoot_words()

感謝您的時間和支持,

正如評論中提到的@match, ABC幾乎相同,並且可能是相同 class 的實例。

有很多方法可以做到這一點,但這里是 class 的一個示例:

from dataclasses import dataclass

@dataclass
class myClass:
    num : int = None
    word : str = None

    def __post_init__(self):
        
        # Determine `match` based on whether a number or word was passed
        self.match = "number" if self.num is not None else "word"        
    
    def shoot(self):

        if self.match=="number":
            return self._shoot_number()
        elif self.match=="word":
            return self._shoot_word()
        
    def _shoot_number(self):
        return self.num
    
    def _shoot_word(self):
        return self.word

然后,您可以創建 class 的實例列表,而不是創建AllClasses

my_classes = [
    myClass(num=10),
    myClass(num=20),
    myClass(word="Some beautiful word"),
]

然后打印數字或單詞:

for my_class in my_classes:
    print(my_class.shoot())

但是,如果這不符合您想要實現的目標,請編輯您的問題以提供更詳細的描述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM