Home > Mobile >  Creating a default constructor from another class in Python
Creating a default constructor from another class in Python

Time:11-05

I have two classes that I created:

class MyBaseClass(object):

    string_a = None
    string_b = None

    def __init__(self):
        self.string_a = str()
        self.string_b = str()

class MyClass(object):

    my_strings = None

    def __init__(self):
        my_strings = List[MyBaseClass]

This seems to create them fine but I try to append a list in my code and the my_strings is None always occurs:

my_class = MyClass()

# Errors here since the my_class.my_strings is None still
my_class.append("heelo", "world")

How do I create a default List[MyBaseClass] that isn't None but has 0 objects in it?

CodePudding user response:

what about this

class MyBaseClass(object):
    string_a = None
    string_b = None

    def __init__(self, a, b):
        self.string_a = a
        self.string_b = b


class MyClass(object):
    my_strings: List[MyBaseClass] = None

    def __init__(self):
        self.my_strings = []


my_class = MyClass()

my_class.my_strings.append(MyBaseClass("heelo", "world"))

print(my_class.my_strings[0].string_a)
print(my_class.my_strings[0].string_b)  

CodePudding user response:

In Python lists don't have a type. Also see this question.

A working version of your example could look like this:

class MyBaseClass(object):

    def __init__(self, a='', b=''):

        self.string_a = a
        self.string_b = b


class MyClass(object):

    def __init__(self):

        self.my_strings = list()

    def append(self, a, b):

        self.my_strings.append(MyBaseClass(a, b))


my_class = MyClass()
my_class.append("heelo", "world")

You were also asking about a default constructor. A simple way to achieve this is by using default arguments, as in the MyBaseClass constructor above.

  • Related