我们都知道python的版本不同,在使用的时候就有所区别。鉴于我们推荐小伙伴们选择python3版本,所以这方面的区别了解的不是很多。就拿_new_来说,在python2和3中的写法是不一样的,之前有接触_new_的小伙伴想必没有注意到这个问题。接下来讲讲new的基本用法,然后就python不同版本中_new_的区别带来详解。
1.new方法接受的参数虽然也是和init一样,但init是在类实例创建之后调用,而 new方法正是创建这个类实例的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Person(object):
"" "Silly Person" ""
def __new__(cls, name, age):
print '__new__ called.'
return super (Person, cls).__new__(cls, name, age)
def __init__(self, name, age):
print '__init__ called.'
self.name = name
self.age = age
def __str__(self):
return '<Person: %s(%s)>' % (self.name, self.age)
if __name__ == '__main__' :
piglei = Person( 'piglei' , 24)
print piglei
|
2.Python3和 Python2中__new__使用不同
Python3的写法
1 2 3 4 5 6 | class Singleton(object):
def __new__(cls,*args, **kwargs):
if not hasattr(cls, '_inst' ):
print(cls)
cls._inst = super (Singleton, cls).__new__(cls)
return cls._inst
|
如果Python3的写法跟Python2写法一样,那么倒数第二行会报错
1 | "TypeError: object() takes no parameters"
|
根据上面的运行结果我们可以发现,在python3中强行使用python2的写法是不可行的。如果有小伙伴是习惯了python2的用法,换版本时要注意_new_写法的改变。