patternpythonMinor
Python custom list class initialization
Viewed 0 times
custompythonlistinitializationclass
Problem
Consider the class
Can this code be improved to avoid instantiating
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:
Other notes:
Demo:
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:
listis a bad variable name as it is shadowing the built-inlistkeyword
- 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.