简体   繁体   中英

Python class derived from built-in type won't construct: TypeError: type() takes at most X arguments (Y given)

Python 2.7, Windows7x64.

The code. Note that class ImmedVal derives from built-in type long .

class Immediate(object):
    def __init__(self, name, value, loc):
        object.__init__(self)
        self.value = value
        self.loc = loc
        self.name = name

class ImmedVal(long, Immediate):
    def __init__(self, name, value, loc):
        long.__init__(self, value)
        Immediate.__init__(self, name, value, loc)

But attempts to instantiate ImmedVal...

x = ImmedVal('hello', 33, 7)

... don't work:

TypeError: long() takes at most 2 arguments (3 given)

All different combinations of numbers/types of parameters on construction don't work.

PS: I'm doing this so referencing it returns the value, so I can use it as such:

eval('x + 1', { 'x' : x })

That built-in type is immutable. That changes the game, and I need the __new__ operator as such:

class ImmedVal(long, Immediate):
    def __new__(cls, name, value, loc):
        return long.__new__(cls, value)

    def __init__(self, name, value, loc):
        long.__init__(self, value)
        Immediate.__init__(self, name, value, loc)

(Base class Immediate and __init__ are unchanged from above.)

Construction, as above, now works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM