0

I dont understand how changed type from list to dict on constructor in main class if i got to subclass another type - dict.

What is magic is this?

class Adder:
def __init__(self, data = [ ]):
    self.data = data
def __add__(self, other):
    return "Not Implemented"



class DictAdder(Adder):
    def __add__(self, y):
        z = {}
        for k in self.data.keys(): z[k] = self.data[k]
        for k in y.keys(): z[k] = y[k]
        return z




y = DictAdder({1:'a', 2:'b'})
l = y + { 3: 'c', 4: 'd'}
print(l)

and answer:

 {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

Pycharm show what self.data.keys() dont have attribute keys() and this must be try, because data is a list, but this is work

Vlad Pakin
  • 43
  • 1
  • 5
  • Variables don't have types in Python. A variable can be used to point to any type of object: `x = 1; x = []; x = 'foo'`. – Ashwini Chaudhary Nov 22 '14 at 21:21
  • 1
    Also [don't use a mutable default argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument), otherwise you might end up posting another question in a while. :-) – Ashwini Chaudhary Nov 22 '14 at 21:23

1 Answers1

0

data defaults to a list, but Python isn't a statically typed language so it doesn't have to be. data is just a name. Just because we have this:

class Adder:
    def __init__(self, data = [ ]):
        self.data = data

Doesn't limit our usage. I can still do:

i = Adder(4)
s = Adder('hello')
d = Adder({1: 2})
o = Adder(SomeOtherType())

As long as whatever uses Adder.data uses it correctly for the type it happens to be. Since in this case, DictAdder interprets data as a dict, and it is, that works fine. Of course, if you tried to use a DictAdder constructed with a non-dict, you would get an error.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • yes, i have error if get list or another type to DictAdder. But, this is good solution as i write? Or is there another solution? – Vlad Pakin Nov 22 '14 at 21:19