phil
phil

Reputation: 565

How do i declare my class so i can access like this

In micropython there is a module neopixel to interact with ws2812 addressable LEDs an example code is

from microbit import *
import neopixel

pixel = neopixel.NeoPixel(pin0, 64)

pixel[0] = (255, 0, 0)
pixel.show()

This declares 64 leds controlled by pin0, sets the first one to red and updates the led array.

How do i declare a class so i can just assign values like the line pixel[0] = (255, 0, 0) ?

Upvotes: 2

Views: 163

Answers (2)

fafl
fafl

Reputation: 7385

Your class needs to implement the __setitem__ method.

From the documentation:

object.__getitem__(self, key)

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

Note: for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.

object.__setitem__(self, key, value)

Called to implement assignment to self[key]. Same note as for __getitem__(). This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. The same exceptions should be raised for improper key values as for the __getitem__() method.

Upvotes: 2

Born Tbe Wasted
Born Tbe Wasted

Reputation: 610

Although the __setitem__ is correct, adding getter and setter is quite recurrent in coding.

I would personaly recommend using attr : http://www.attrs.org/en/stable/examples.html

This enables tons of magic , and setter are included in the functionnalities.

After pip install attrs

import attr
@attr.s
class dummy():
    x= attr.ib()
test = dummy ([0])
test.x[0] = 2
test

Upvotes: 2

Related Questions