TypeError: object.__new__(int) is not safe, use in

2019-05-07 11:00发布

问题:

While reading this: What is a metaclass in Python?, I am learning to use __new__ using the following snippet:-

class a(object):
    pass

a.__new__(int,'abcdef',(int,),{})

There could be some problem in calling __new__ using a.. But, I get the following error, the meaning of which I do not understand:-

TypeError: object.__new__(int) is not safe, use int.__new__()

If there is something to do with the usage of __new__, I can ammend that by reading some books. But, can someone please explain why this message comes:

object.__new__(int) is not safe, use int.__new__()

回答1:

Put simply, prior to 2.6 - object.__new__ ignored arguments... Now it actually may do something with them... So the warning is that something different may happen.

This post Any ideas about the best work around for __new__ losing its arguments? - has a much more detailed explanation.

You probably also want to be looking at http://docs.python.org/library/functions.html#type

Knowing what's possible with all the meta stuff in Python is great, but just as a warning, I wouldn't get too hung up about it - as I've seen some really "clever" solutions, that are just monstrosities...