在实例化子类

时间:2017-07-09 19:44:59

标签: python python-3.x inheritance

我正在学习python中的继承, 我有一个名为Cipher的Super类,我期待 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'
请帮忙。

2 个答案:

答案 0 :(得分:2)

您需要首先调用超类的 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.

答案 1 :(得分:1)

您在检查__init__之后调用父self.secret_string方法。只需在子__init__方法中执行此操作,或在测试其长度时未定义self.secret_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")

请注意,您只需执行以下操作即可测试长度:

if not self.secret_string: