How to Overload Generators

Asked 2 years ago, Updated 2 years ago, 95 views

I know that you can't make multiple _init__ in Python class So how do I overload the constructor?

My source code is

You have to. Source Code 1 has two _init__ so it does not run properly Source code 2 works well, but it seems like it's a expedient.

class myClass1(object):
    def __init__(self):
        self.myvalue = 3;
    def __init__(self, num):
        self.myvalue = num


o = myClass1() #Error
o = myClass1(1)
class myclass2(object):
    def __init__(self, num = 3):
        self.myvalue = num

python coding-style

2022-09-21 19:45

1 Answers

You can solve it by writing None as follows.

class myClass1(object):
    def __init__(self, num=None):
        num = 3 if num is None else num

If you don't want to limit the parameters

class myClass1(object):
    def __init__(self, *args, **kwargs):
        #args -- a tuple that stores unnamed factors
        # #kwargs -- a dict that stores the named factor with a name
        print "aargs:", args
        print "kwargs:", kwargs
        mynum = 3 if kwargs['num'] is None else kwargs['num']

o = myClass1(3, "hello", num = 1, mystring = "mystring")

Results)

aargs: (3, 'hello')
kwargs: {'mystring': 'mystring', 'num': 1}

When you write (*args, **kwargs), you must first write an unnamed factor, and then an unnamed factor.

That is,

o = myClass1(3, "hello", num = 1, mystring = "mystring") : ok o = myClass1("hello", num = 1, mystring = "mystring", 3) : not ok o = myClass1("hello", num = 1, 3, mystring = "mystring") : not ok


2022-09-21 19:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.