I want to enhance the following artificial example
class Record:
def __init__(self, data):
self.data = data
def filter(self, positive = False, even = False):
data_ = self.data
if positive:
data_ = [c for c in data_ if c>0]
if even:
data_ = [c for c in data_ if c % 2 ==0]
self.data = data_
data = list(range(-5,10,1))
record = Record(data)
record.filter(positive=True, even=True)
print(record.data)
which prints correctly [2,4,6,8]
, so that it would be possible to request filtering upon initialisation of the Record instance. My approach is
class Record:
def __init__(self, data, filter = {}):
self.data = data
if len(filter) > 0:
self.filter(**filter)
def filter(self, positive = False, even = False):
data_ = self.data
if positive:
data_ = [c for c in data_ if c>0]
if even:
data_ = [c for c in data_ if c % 2 ==0]
self.data = data_
data = list(range(-5,10,1))
record = Record(data,filter={positive:True, even:True})
print(record.data)
and (naturally...) I get the error NameError: name 'positive' is not defined
.
How to proceed here, and also is it, in general, a right idea to embed a method into initialisation?
CodePudding user response:
You don't have to create a dictionary to pass the arguments. This would work too:
class Record:
def __init__(self, data, **args):
self.data = data
self.filter(**args)
def filter(self, positive=False, even=False):
...
f1 = Record(data) # both positive and even will be False
f2 = Record(data, positive=True)
f3 = Record(data, even=True)
f4 = Record(data, even=True, positive=True)
This has the added benefit that you treat even
and positive
consistently throughout your code, avoiding having to quote them as strings at some points.