python: return list method takes index as arguments -


i'm wondering if pseudo coded below possible:

def getlst(index = :):         lst = [1, 2, 3, 4, 5, 6, 7]     return lst[index]   print getlst() >> [1, 2, 3, 4, 5, 6, 7]  print getlst(2) >> 3   print getlst(2:-2) >> [3, 4, 5] 

obviously i'm getting syntaxerror.

the method being used in @ class returning private list.

i know example below possible, , might more correctly (easier read/understand code), since i've got idea of doing first example , wasn't possible got curioss of knowing how make first example work.

def getlst():         lst = [1, 2, 3, 4, 5, 6, 7]     return lst   print getlst() >> [1, 2, 3, 4, 5, 6, 7]  print getlst()[2] >> 3  print getlst()[2:-2] >> [3, 4, 5] 

the 2:-2 notation specific array subscribtion (ie a[2:-2] expression). closest thing if want accept notation use whole notation. done overloading __getitem__ method (if want negatives need overload __len__ well).

class getlist:     def __init__(self, l):         self.l = l      def __getitem__(self, x):         return self.l[x]      def __len__(self):         return len(self.l) 

actually a[2:4] syntactic sugar a[slice(2,4,none)], , a[2:-2] syntactic sugar a[slice(2,len(a)-2,none)]. of course examine slice using x.start, x.stop , x.step (given it's slice of course) , whatever you'd based on that.

if you'd use decorator enable calling function using subscribtion notation:

class subscrfunc:     def __init__(self, f):          self.f = f      def __call__(self, x):          return self.f(x)      def __getitem__(self, x):          return self.f(x)      def __len__(self):          return 0  @subscrfunc def getlst(index):     lst = [1, 2, 3, 4, 5, 6, 7]     retur lst[index]  getlst[2:3] 

note though hack allowing negative stop in slice fake length of 0 result in getlst[2:-2] result in argument being slice(2,-2,none) nonsense list return nothing (instead have manually handle case 1 index negative).


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -