Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Functions vs attributes in object API #378

Closed
@dpgeorge

Description

@dpgeorge

In designing the API for pyboard objects (like accelerometer, servo, LED), there is a choice for some parts of the interface whether it is implemented as a function or an attribute. For example, consider the accelerometer:

accel = pyb.Accel() # create accelerometer object
print(accel.x_fun()) # read x value using a function call
print(accel.x_attr) # read x value using an attribute

Which is better (if there is such a thing)? x_attr is more efficient because it's only 1 call to the underlying C object. x_fun() is 2 calls: 1 to lookup the x_fun method, the other to call it. You only ever need to read the value of the x axis, so there will never be any arguments to x_fun(), thus x_attr will suffice.

It's sensible to consider the axis' as variables. Behind the scenes, the accelerometer is just an I2C device with 10 or so registers. You read and write these registers, and that's it. The first 3 registers are the x, y and z axis values.

Objections against having x_attr is that it changes asynchronously (ie one read then another read will in general give different values, which is not what you expect for an attribute), and that it's read only (no sense in writing the x axis value).

A counter argument is that the mode register (and other settings) are read/write, and only change when you write to them, so they really are proper attributes (as opposed to methods).

Having x_fun() allows you to pass accel.x_fun as a function to be called later on. To do this with x_attr you will need a lambda: lambda:accel.x_attr.

Other objects like Servo could have angle as an attribute, which is sensible to read and write. LED has intensity which acts exactly like an attribute (LED.intensity=128).

Comments?

Metadata

Metadata

Assignees

No one assigned

    Labels

    rfcRequest for Comment

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions