Python - type(name,bases,dict) -
docs:
with 3 arguments, return new type object. dynamic form of class statement. name string class name , becomes
__name__
attribute; bases tuple itemizes base classes , becomes__bases__
attribute; , dict dictionary namespace containing definitions class body , becomes__dict__
attribute.
while learning python have come across use of type "a dynamic form of class statement", seems interesting , useful , wish understand better. can explain role of __name__
, __bases__
, , __dict__
in class , give example type(name, bases, dict)
comes own right.
when define class:
class foo(base1, base2): bar = 'baz' def spam(self): return 'ham'
python this:
def spam(self): return 'ham' body = {'bar': 'baz', 'spam': spam} foo = type('foo', (base1, base2), body)
where foo
added namespace class
statement defined in.
the block under class
statement executed if function no arguments , resulting local namespace (a dictionary) forms class body; in case dictionary 'bar'
, 'spam'
keys formed.
you can achieve same result passing name string, tuple of base classes , dictionary string keys type()
function.
once start exploring metaclasses (which subclasses of type()
, letting customize how classes created), you'll find body
doesn't have plain dictionary. pep 3115 - metaclasses in python 3 expanded possible values dict like, letting implement sorts of interesting class behaviour letting use augmented dictionaries class body. new python 3.4 enum
module example, uses ordereddict()
instance instead, preserve attribute ordering.
Comments
Post a Comment