HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python custom list class initialization

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
custompythonlistinitializationclass

Problem

Consider the class AB below that is to be used as a simple customized list of A objects for lookup operations.

Can this code be improved to avoid instantiating AB with an empty list [] (i.e., perhaps modify __add__ in some way)?

class A():
    def __init__(self, arg):
        self.arg = arg

class AB():
    def __init__(self, list):
        self.list = list

    def __add__(self, other):
        return AB(self.list + [other])

ab = AB([])
ab += A(1)
ab += A(2)

Solution

Sure, you can play with the default argument value:

class AB:
    def __init__(self, data=None):
        self.data = data if data is not None else []

    def __add__(self, other):
        return AB(self.data + [other.arg])


Other notes:

  • list is a bad variable name as it is shadowing the built-in list keyword



  • remove redundant parentheses after the class name



Demo:

In [1]: ab = AB()

In [2]: ab += A(1)

In [3]: ab += A(2)

In [4]: print(ab.data)
[, ]

Code Snippets

class AB:
    def __init__(self, data=None):
        self.data = data if data is not None else []

    def __add__(self, other):
        return AB(self.data + [other.arg])
In [1]: ab = AB()

In [2]: ab += A(1)

In [3]: ab += A(2)

In [4]: print(ab.data)
[<__main__.A instance at 0x10afb14d0>, <__main__.A instance at 0x10afa0998>]

Context

StackExchange Code Review Q#154748, answer score: 2

Revisions (0)

No revisions yet.