Python seems disallow you to assign attribute to the internal highest level of 'object':
object.lst=lambda o:list(o)
Or
func=lambda o:list(o)
setattr(object,'lst',func)
All generate error messages.
Any design reason behind it? Honestly, this is odd, since everything is an object, and you can define func(obj)
as you wish, so if func is not constraint the argument type, why the method way is prohibited to add then?
obj.func()
is exactly func(obj) if you assign the func as an attribute to the object
. Since everything is an object,an attribute of the object is a global function almost by definition.
Anyway to walk-around?
Basically if you have the capability to add some functions to build-in types, you can do pipeline style programming:obj.list().len().range()
and I think the readibility of this type program is very clear and nothing non-pythonic.
I am not sure at the moment at the actual "design" reasoning for this, though there are - but the fact is that object, as some other built-in classes are written in native code (called "built-in") -
Due to the nature these built-in classes are made (their code is usually in C), they do not have a __dict__
attribute themselves, and thus, disallow arbitrary parameter setting.
Function objects had a __dict__
attribute implemented somewhere along the 2.x development cycle, so they can hold arbitrary attributes.
The way to go if you need something that works as an "object" but have arbitrary attributes is to subclass object, and add your attributes there:
class MyObj(object): pass
MyObj.lst = lambda o: list(o)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With