开发者

How come this Python method does not have "self"?

开发者 https://www.devze.com 2023-03-21 07:05 出处:网络
class MM(dict): def __init__(self, indexed, *args, **kwargs): super(MM, self).__init__(*args, **kwargs) #must do it.
class MM(dict):
    def __init__(self, indexed, *args, **kwargs):
        super(MM, self).__init__(*args, **kwargs) #must do it.
        self['name'] = 'hello, this is a value'
        self.go()

    def go(self, kwargs):
        print kwargs #I want this to print out the kwargs

How come this class creates an error when I try to initalize it?

>> m = MM()

TypeError: metaMod_Distance() t开发者_运维问答akes exactly 2 arguments (1 given)


You probably want to do:

def go(self, **kwargs):
    print kwargs

To take keyword only arguments. So the function call will work.

Also you have to pass something else to your constructor (because of unused argument indexed):

m = MM(1) #or whatever


The error is straightforward. You're short one argument. You need to pass in a value for indexed.


Modify your code the following way:

class MM(dict):
    def __init__(self, *args, **kwargs):
        super(MM, self).__init__(*args, **kwargs) #must do it.
        self['name'] = 'hello, this is a value'
        print kwargs
        # Or since you class is subclass of dict
        print self

Then

m = MM() #will work

But if indexed is property you really need then do not forget to specify value for it while creating class:

class MM(dict):
    def __init__(self, indexed, *args, **kwargs):
        super(MM, self).__init__(*args, **kwargs) #must do it.
        self['name'] = 'hello, this is a value'
        self.indexed = indexed
        print kwargs
        # Or since you class is subclass of dict
        print self

Then:

indexed = True #since i don't know it's datatype
m = MM(indexed)


I am not sure exactly what you are trying to do, but

  1. __init__ of MM has indexed as a arg, which you need to specify when creating an object.
  2. Also go method should send a argument when called from init. So, in effect this would not give you any problem.

    class MM(dict):
    
        def __init__(self, indexed, *args, **kwargs):
            super(MM, self).__init__(*args, **kwargs) #must do it.
            self['name'] = 'hello, this is a value'
            self.go(kwargs)
    
        def go(self, kwargs):
            print kwargs #I want this to print out the kwargs
    
     m = MM('goone')
    
0

精彩评论

暂无评论...
验证码 换一张
取 消