Class Variables, Access, and Persistence
Newbie/novice Python guy here. I'm trying to avoid using global variables, and in some of my searches I was pointed in the direction of Class variables. But I'm struggling with scope and persistence. I simplified the code segment below, but its basically what I'm trying to do.
I have a sensor I need to run a long average on to handle the dither (variation). I want to keep the list/array of measures within the class and/or def and retain them between subsequent calls to the method/function. However when I run sensor.setup() I get an error "offset" is not defined. I assumed it would have been created with the instance and accessable by it's member setup(). :(
Is there a link to some good examples? Or if there is a better way I'm all ears!
I have a sensor I need to run a long average on to handle the dither (variation). I want to keep the list/array of measures within the class and/or def and retain them between subsequent calls to the method/function. However when I run sensor.setup() I get an error "offset" is not defined. I assumed it would have been created with the instance and accessable by it's member setup(). :(
Is there a link to some good examples? Or if there is a better way I'm all ears!
Code: Select all
class myClass:
range_mm = 0.0
average = 0.0
offset = 0
def setup():
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_vl6180x.VL6180X(i2c, offset)
return sensor
def read():
# read sensor
return range_mm
def read_algo():
read()
# stats and magic here
average = X
def main():
sensor = myClass() # create instance of the class
sensor.setup()
if __name__ == "__main__":
main()
Re: Class Variables, Access, and Persistence
Look for a tutorial on classes, e.g. https://www.w3schools.com/python/python_oop.asp
When accessing class 'MyClass" property "my_member ", use either
- self.my_member when my_member is owned by a class instance
- MyClass.my_member is a class property
- my_member without "self." or "MyClass." is a variable in a method.
When accessing class 'MyClass" property "my_member ", use either
- self.my_member when my_member is owned by a class instance
- MyClass.my_member is a class property
- my_member without "self." or "MyClass." is a variable in a method.
- jungle_jim
- Posts: 22
- Joined: Sun Oct 22, 2023 2:59 pm
Re: Class Variables, Access, and Persistence
Some reading on scope: https://www.w3schools.com/python/python_scope.asp
In your simplified example though, there is nothing being passed to the methods within the class, so they have no way of accessing anything outside of their scope. Just like a standalone function, if you don't give it a reference (even if its a method defined within the class) anything that's done within that method scope will be treated as a new variable.
The link ghp posted covers all of this better than i ever could.
In your simplified example though, there is nothing being passed to the methods within the class, so they have no way of accessing anything outside of their scope. Just like a standalone function, if you don't give it a reference (even if its a method defined within the class) anything that's done within that method scope will be treated as a new variable.
The link ghp posted covers all of this better than i ever could.
Re: Class Variables, Access, and Persistence
I'm pretty amateur (and already late), but you'll want to look at the __init__ method of a Python class.
There is (was?) a trap when using default lists or dictionaries with classes. I can't remember the particulars and I haven't been using Python (or even barely coding) much lately, but definitely look it up. Think it caught me out once or twice and sometimes can be very subtle.
Lastly, I think you'll want to log the readings in an external file. If there is ever a shut down, all the data over days/months is gone. Maybe a `number_of_readings` and `current_average` as well, so you're just appending a new reading to one file, and doing a single read of two numbers and much simpler calculation to get a new average from a different file. Keeps all your raw data, and a rolling average. mcoding (youtube) did a great tutorial on logging if your log files are expected to get big and require multiple, automated ... stuff, but I'd imagine you'd get away with just the built-in file handling functions (open(), etc)) or the pathlib one and write to a new file based on the datetime.now(timezone.utc)'s month if the file doesn't already exist.
(Maybe also if you're using the built-in function of open.read(), you might want to rename your class's function just to make it clear that one is to read the sensor.)
There is (was?) a trap when using default lists or dictionaries with classes. I can't remember the particulars and I haven't been using Python (or even barely coding) much lately, but definitely look it up. Think it caught me out once or twice and sometimes can be very subtle.
Lastly, I think you'll want to log the readings in an external file. If there is ever a shut down, all the data over days/months is gone. Maybe a `number_of_readings` and `current_average` as well, so you're just appending a new reading to one file, and doing a single read of two numbers and much simpler calculation to get a new average from a different file. Keeps all your raw data, and a rolling average. mcoding (youtube) did a great tutorial on logging if your log files are expected to get big and require multiple, automated ... stuff, but I'd imagine you'd get away with just the built-in file handling functions (open(), etc)) or the pathlib one and write to a new file based on the datetime.now(timezone.utc)'s month if the file doesn't already exist.
(Maybe also if you're using the built-in function of open.read(), you might want to rename your class's function just to make it clear that one is to read the sensor.)
Jump to
- Community
- General discussion
- Announcements
- Other languages
- Deutsch
- Español
- Français
- Italiano
- Nederlands
- 日本語
- Polski
- Português
- Русский
- Türkçe
- User groups and events
- Raspberry Pi Official Magazine
- Using the Raspberry Pi
- Beginners
- Troubleshooting
- Advanced users
- Assistive technology and accessibility
- Education
- Picademy
- Teaching and learning resources
- Staffroom, classroom and projects
- Astro Pi
- Mathematica
- High Altitude Balloon
- Weather station
- Programming
- C/C++
- Java
- Python
- Scratch
- Other programming languages
- Windows 10 for IoT
- Wolfram Language
- Bare metal, Assembly language
- Graphics programming
- OpenGLES
- OpenVG
- OpenMAX
- General programming discussion
- Projects
- Networking and servers
- Automation, sensing and robotics
- Graphics, sound and multimedia
- Other projects
- Media centres
- Gaming
- AIY Projects
- Hardware and peripherals
- Camera board
- Compute Module
- Official Display
- HATs and other add-ons
- Device Tree
- Interfacing (DSI, CSI, I2C, etc.)
- Keyboard computers (400, 500, 500+)
- Raspberry Pi Pico
- General
- SDK
- MicroPython
- Other RP2040 boards
- Zephyr
- Rust
- AI Accelerator
- AI Camera - IMX500
- Hailo
- Software
- Raspberry Pi OS
- Raspberry Pi Connect
- Raspberry Pi Desktop for PC and Mac
- Beta testing
- Other
- Android
- Debian
- FreeBSD
- Gentoo
- Linux Kernel
- NetBSD
- openSUSE
- Plan 9
- Puppy
- Arch
- Pidora / Fedora
- RISCOS
- Ubuntu
- Ye Olde Pi Shoppe
- For sale
- Wanted
- Off topic
- Off topic discussion