global name 'self' is not defined - noob trying to learn

Hrvoje Niksic hniksic at xemacs.org
Mon Mar 30 04:25:11 EDT 2009


mark.seagoe at gmail.com writes:

> So I want a class ShadowRegister, which just has a value that I can
> do get/set bit sel and slice ops.  I got that working with __init__.
> It was subclass from "object".  Then I wanted a RegisterClass that
> was a subclass of ShadowRegister, which would read a hardware
> register before doing get bit sel/slices, or read HW reg, do set bit
> sel/slice, but when I try to print in hex format ('0x016X') it said
> it required an int (but the ShadowRegister class had no issues).
> Then I was told instead of using object I could subclass as long
> (seemed the only solution for Python 2.5).  Then when I started to
> want to add my own init code (like register length in bits), I was
> told I should use __new__ instead of __init__.  So but ever since
> then I've noticed that my value is not changing from the initially
> set value.  I'm really cornfused now.

I think I understand your problem.  The short story is: if you derive
from int or long, you won't be able to change the "value" because the
underlying value is immutable.  To get mutable values, you'll need to
subclass object and implement the int-like functionality you need.
Fortunately, this is quite easy.

I assume that by "print in hex format" you're referring to the %
operator, such as '%x' % your_instance.  For it to work, you need to
define an __int__ method (not to be confused with __init__!), which
will get called when coercion to integer is required.  For example:

class Foo(object):
  def __init__(self, initval=0):
    self._value = initval
  # a bunch of methods for getting/setting bits
  def __int__(self):
    return self._value

>>> x = Foo(100)
>>> '0x%x' % x
'0x64'
>>> x._value = 1000    # in real code you'd do this by setting the
                       # bits or whatever
>>> '0x%x' % x
'0x3e8'



More information about the Python-list mailing list