variable scope of class objects

JonRob JonRob
Mon Oct 19 14:39:36 EDT 2015


Hi,

I've having trouble understanding the self concept as it applies to
variables.  I think I understand how it affects methods.

I haven't been able to fully grasp the scope of class variables and
the effect of the "self"  to the scope of the variable.

I (think) I understand that in the below case, the word self could be
replaced with "BME280" to explicitly call out a variable.

But even still I don't know how explicit call out effects the scope of
a variable.

The below pseudo code is distilled from my 1st attempt at a functional
Python program on the RasPi.

My questions are:
What is the scope of class variables?
does the self. prefix modify this scope?

Thanks

Regards

JonRob




#!/usr/bin/python
# -- developed using Python 2.7.3

class BME280:

# all the below are class variables
# those preceded by an underscore are predefined to some constant
# those without the underscore are to be "working" variables.

    _regT1       = 0x88
    _regH6       = 0xE7
    _coeff_P2    = 0x82
    _coeff_P6    = 0x32
    
    filter       = 0    #should these be "self"?
    t_fine       = 0
    
    def __init__(self, address=0x76, debug=True):
        self.i2c = Adafruit_I2C(address)
        self.address = address
        self.debug = debug
                
    def pressure_calc(self):
        var1 = self.i2c.readU16(self._regT1,False)
        p = (1048576.0 - var1) * _coeff_P2
        return p
        
    def read_pressure(self):      #called  by main application
        pressure_hPa = pressure_calc(self) /10 
        # apply compensation
        return pressure_hPa
                



More information about the Python-list mailing list