0

I need to use some float-type variables for two purposes: 1. To use it`s values for calculation of some function, 2. To change the values of these variables theirselves. I know how to do it generally, but I need to have simple short notation for my float-type variables. In the trivial example below I add two numbers, and my aim is to be able to write smth like 'f(a, i)' instead of 'a.vals[a.define_index[i]]' in the example below. I need to write simple notation both from left of '=' and from right of '=':

import numpy as np
class SomeClass(object):
    def __init__(self):
        self.vals=np.ones(10)
        self.define_index=[]
        for i in range(10):
            self.define_index.append(10-1-i)
a=SomeClass()
for i in range(10):
    a.vals[a.define_index[i]]=a.vals[a.define_index[i]]+1
print('sums =', a.vals)

1 Answer 1

2

Seems you want to implement __getitem__ and __setitem__ for your type. It allows you to call a[i]. Doing so makes your type look like a list, so you might want to implement __iter__ as well so you could iterate over it with for loop.

import numpy as np
class SomeClass(object):
    def __init__(self):
        self.vals=np.ones(10)
        self.define_index=[]
        for i in range(10):
            self.define_index.append(10-1-i)

    def __getitem__(self, i):
        return self.vals[self.define_index[i]]

    def __setitem__(self, i, value):
        self.vals[self.define_index[i]] = value

    def __iter__(self):
        for i in self.define_index:
            yield self.vals[i]

a=SomeClass()
for i in range(10):
    a[i] += 1
print('sums =', a.vals)

for val in a: # iterate over data, hiding define_index
    print(val)

PS. I've shortened your incrementation to += 1

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.