I constructed a class:
class Foo (object):
def __init__(self,List):
self.List=List
@property
def numbers(self):
L=[]
for i in self.List:
if i.isdigit():
L.append(i)
return L
@property
def letters(self):
L=[]
for i in self.List:
if i.isalpha():
L.append(i)
return L
>>> inst=Foo(['12','ae','45','bb'])
>>> inst.letters
['ae', 'bb']
>>> inst.numbers
['12', '45']
How can I add attributes so I could do inst.numbers.odd that would return ['45']?
Your
numbersproperty returns a list, so anumbers.oddwon’t work.However, you could follow a workflow like:
define a small class
Numbers, that would define two propertiesevenandoddFor example,
Numberscould take a list as argument of its__init__, theevenproperty would return only the even number of this list[i for i in List if int(i)%2 == 0](andoddthe odd ones)…create an instance of
Numbersin yourFoo.numbersproperty (using yourFoo.Listto initialize it) and return this instance…Your
Numbersclass could directly subclass the builtinlistclass, as suggested. You could also define it likeHere, we returning the representation of
Numbersas the representation of itsLattribute (a list). Fine and dandy until you want to append something to aNumbersinstance, for example: you would have to define aNumb.appendmethod… It might be easier to stick with makingNumbersa subclass of list:Edited: corrected the
//by a%, because I went too fast and wasn’t careful enough