1

I am trying to implement a Setting class that should hold global settings for my application. From the base class I want to derive classes that should hold the actual setting value, can be int, str and so one... This looks like:

class Setting:
    def __init__(self):
        pass


class SettingInt(Setting, int):
    """
    An int setting.
    """
    def __init__(self, val = 0, **kw):
        int.__init__(self, val, **kw)
        Setting.__init__(self)

But when the SettingInt is used as

i = SettingInt(0, ul = 1)

I get an error:

TypeError: 'ul' is an invalid keyword argument for this function

Why?

Robert
  • 725
  • 1
  • 7
  • 15
  • 1
    Why `int.__init__(self, val, **kw)` and not `int.__init__(self, val)`? – Dan D. Aug 12 '15 at 20:03
  • Neither `int` or `Setting` know what to do with a `ul` keyword argument. What's your intention (what are you trying to accomplish)? – martineau Aug 12 '15 at 20:19
  • You should really avoid subclassing built-in types like that. Why do you want to do that? What are you trying to accomplish? – Cyphase Aug 12 '15 at 20:24
  • http://stackoverflow.com/questions/3238350/subclassing-int-in-python – Padraic Cunningham Aug 12 '15 at 20:27
  • Ok, thank you, I now understand the Ints are immutable. What I am trying to accomplish is to create a "setting" class that can be used to hold application global settings. These should be writeable/readable to/from file between program runs. My idea was to use a JSON object in the settings file, and if Setting was derived from Int (and other known types), the json module could pickle a global dictionary with Setting variables. I will have to think of another solution I guess. – Robert Aug 16 '15 at 07:02

1 Answers1

2

You can't pass ul as a keyword argument to int, because int doesn't accept such an argument. You need to just callint.__init__(self, val).

It's not clear what you intend the use of that argument to be, but whatever it is, you need to handle it in in your own class, not pass it on to int.

Also, because int is immutable, overriding __init__ will not work for changing the value. You need to override __new__.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Even if I change the line `int.__init__(self, val, **kw)` to `int.__init__(self, val)` I get the same error message. – Robert Aug 16 '15 at 06:52
  • @Robert: That's because of what I said about needing to override `__new__`. – BrenBarn Aug 16 '15 at 07:19