0

I am pretty new to python and saw that we can get a dict by dict.fromkeys(keys, value), I am not sure why here you can use dict, not dict().?

For list and int or str, if use this

list.append(1)
TypeError                                 Traceback (most recent call last)
<ipython-input-40-f15c629423f5> in <module>()
      1 
----> 2 list.append(1)

TypeError: descriptor 'append' requires a 'list' object but received a 'int'

and it doesn't work even with the list object

list.append([1])

TypeError                                 Traceback (most recent call last)
<ipython-input-41-b98586d7f7ed> in <module>()
      1 
----> 2 list.append([1])

TypeError: append() takes exactly one argument (0 given)

if I

type(dict)

return type

what is 'type' type?

this might be a dumb question, but I could not find any answers online, anybody can help?

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Kurt
  • 1
  • 1
  • `dict` is a class (aka type) which creates an object of this type if using call syntax `dict()`. a class/type is itself an object of type `type`. – Michael Butscher Mar 18 '18 at 02:40
  • Unless you've overwritten the type `list` with an actual `list` object, the syntax is `list.append(L, 1)` where `L` is a list. – dROOOze Mar 18 '18 at 02:43

1 Answers1

1

dict.fromkeys is a class method, basically meaning it doesn't need to be attached to an instance of a dict class to work. This makes sense - dict.fromkeys is basically an alternative constructor for a dict.

list.append on the other hand is a regular instance method, meaning we need an actual list instance to call .append on. This also makes sense - appending is an operation that does not precede the creation of a list, i.e. we need a list to append to.

We can also reference instance methods as class attributes, and get back a regular function object that we pass an instance to as the first argument, i.e. list.append(some_list, 'foo').

miradulo
  • 28,857
  • 6
  • 80
  • 93
  • thanks,make a lot of sense now. one more question, why type(dict) return 'type' not something like 'class' or 'class name'? – Kurt Mar 18 '18 at 12:01
  • @Kurt This is a bit of a tricky question, but the short answer is because `dict` is actually an instance of a `type` class, a [metaclass](https://docs.python.org/3/reference/datamodel.html?highlight=metaclass#metaclasses) that creates instances of `dict`'s for us! Notice that `dict().__class__.__class__` is `type` too. This is an advanced topic in Python, a good overview is found in e-satis' answer [on this question](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python). – miradulo Mar 18 '18 at 15:39