简体   繁体   中英

Python27: Subclassing a class by using type

I have the following class

class Sample(object):
    def __init__(self, argument, argument2, argument3):
        self.value = argument
        self.value2 = argument2
        self.value3 = argument3

and I want to create a subclass of this by using type however I am not sure on how to populate the arguments to the __ init __ method.

I also have this custom __ init __ method which populates the object:

def setup(self, arg, arg2, arg3):
    self.value = "good"
    self.value2 = "day"
    self.value3 = "sir"

myclass = type("TestSample", (Sample,), dict(__init__=setup))

however when I perform:

myclass()

I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: setup() takes exactly 4 arguments (1 given)

Is there a way to pre-stuff these values in without having to provide them at object instatiation?

Your subclass is working fine, but you gave it their own __init__ method that still takes four positional arguments . One of those is self , but you still need to provide the other 3 when creating the object:

myclass('some', 'argument', 'values')

Your function is ignoring those arguments otherwise, so perhaps you meant to not include them in the function signature? You don't have to match the parent class here:

def setup(self):
    self.value = "good"
    self.value2 = "day"
    self.value3 = "sir"

myclass = type("TestSample", (Sample,), dict(__init__=setup))

Instead of setting the attributes directly, you could delegate that to the parent class still:

def setup(self):
    Sample.__init__(self, 'good', 'day', 'sir')

myclass = type("TestSample", (Sample,), dict(__init__=setup))

If you wanted these to be defaults that you can override, use keyword arguments:

def setup(self, argument='good', argument2='day', argument3='sir'):
    Sample.__init__(self, argument, argument2, argument3)

myclass = type("TestSample", (Sample,), dict(__init__=setup))

Now you can either omit the arguments, or provide different values for them:

c1 = myclass()
c2 = myclass(argument2='weekend')

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