我正在学习python中的继承,
我有一个名为Cipher的超级类,并且我希望init函数具有secret_string属性,我创建了一个新类Keyword,它继承了Cipher,在子类的init中,当我创建子类的实例时,我正在调用超类的init在传递必需的属性,但这给了我一个属性类型错误。

主类:

 import csv
    import logging

    logging.getLogger().setLevel(logging.INFO)


    class Cipher:
        secret_numbers = []
        orig_dict = {}

        def __init__(self, secret_string, *args, **kwargs):
            # field_names = ["alpha", "posit"]

            self.secret_string = secret_string

            with open("original_assigned.csv", "r") as orig_csv:
                reader = csv.DictReader(orig_csv)
                for row in reader:
                    for k, v in row.items():
                        self.orig_dict[k] = v
                logging.info(self.orig_dict)

            for letter in secret_string:
                self.secret_numbers.append(self.orig_dict.get(letter))

        def get_secret_numbers(self):
            return self.secret_numbers


子类:-

class Keyword(Cipher):
    converted_string = []

    def __init__(self, secret_string, *args, **kwargs):
        if len(self.secret_string) < 1:
            raise ValueError("Secret string cannot be empty")
        super().__init__(secret_string)

    @property
    def convert_to_keyword_string(self):
        for num in self.secret_numbers:
            for k, v in self.orig_dict:
                if num == v:
                    self.converted_string.append(k)
        return self.converted_string


实例创建:-

key = Keyword(["A", "B", "C", "D"])


错误:-

Traceback (most recent call last):
  File "/Users/Documents/workspace/secret_message/cipher.py", line 52, in <module>
    key = Keyword(["A", "B", "C", "D"])
  File "/Users/Documents/workspace/secret_message/cipher.py", line 34, in __init__
    if len(self.secret_string) < 1:
AttributeError: 'Keyword' object has no attribute 'secret_string'


请帮忙。

最佳答案

您需要先调用超类的init,然后才能访问它设置的属性:

class Keyword(Cipher):
    converted_string = []

    def __init__(self, secret_string, *args, **kwargs):
        super().__init__(secret_string)
        if len(self.secret_string) < 1:
            raise ValueError("Secret string cannot be empty")


或执行:

class Keyword(Cipher):
    converted_string = []

    def __init__(self, secret_string, *args, **kwargs):
        if len(secret_string) < 1:
            raise ValueError("Secret string cannot be empty")
        super().__init__(secret_string)


(即删除self.

关于python - 在子类实例化期间获取AttributeError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45000350/

10-15 12:48