Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

__metaclass__, __new__ 和 __init__ 的解释有点小问题 #5

Open
xxleyi opened this issue May 26, 2019 · 0 comments
Open

__metaclass__, __new__ 和 __init__ 的解释有点小问题 #5

xxleyi opened this issue May 26, 2019 · 0 comments

Comments

@xxleyi
Copy link

xxleyi commented May 26, 2019

BAT_interviews/Python面试题及答案.md at master · lengyue1024/BAT_interviews

__new__和__init__ 解释:

__metaclass__是创建类时起作用.所以我们可以分别使用__metaclass__,__new__和__init__来分别在类创建,实例创建和实例初始化的时候做一些小手脚.

此处有点小问题:元类中也有 __new__,在类创建时也会调用一次,类中的 __new__ 其实是继承自元类(可以通过重写添加行为),只有在重写过的情况下才会在每次新建实例时调用一次。这样一来,说 __new__ 在实例创建时做一些小手脚就有一丢丢的误导性。

修正:__new__ 作为 object 中就存在的静态方法,在类创建和实例创建时,均会调用,并可以通过重写定制类创建和实例创建的具体行为。

class T:
    pass

t = T()
t.__new__ is T.__new__ # True
T.__new__ is object.__new__ # True
@xxleyi xxleyi closed this as completed May 26, 2019
@xxleyi xxleyi reopened this May 26, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant