D
D
Daniil Kolesnichenko2015-06-24 18:54:04
Python
Daniil Kolesnichenko, 2015-06-24 18:54:04

Can a Python class mimic the behavior of an array?

Is it possible in Python 3.x to set a class to refer to its instance as an array:

class A():
    ...

a = A()
a[1]    # нужно чтобы можно было вот так обращаться к экземпляру класса

Ideally, get and set methods are needed for elements that are retrieved as in the code above. I did not find the necessary magic methods. Can this be done somehow?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman, 2015-06-24
@KolesnichenkoDS

Yes, of course it can. Define the __iter__ and __getitem__ methods . The first is to be able to use in a loop like for i in a, the second to access a[i]. In the same place there is a description of the __setitem__ method and a lot of other interesting things.

R
Roman Kitaev, 2015-06-24
@deliro

Inherit from the standard list and write your own blackjacks and methods.

T
throughtheether, 2015-06-24
@throughtheether

I did not find the necessary magic methods.

The __getitem__ method will help you .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question