如何给Python构造函数起别名?

问题描述 投票:0回答:1

我在herehere读到Python方法可以使用

=
来别名。

但是,当我用

__init__
方法尝试时,似乎不起作用。

class MyClass:
    def __init__(self):
        print("Hi mum!")
    
    new_name = __init__

a = MyClass()
b = MyClass.new_name()

b = MyClass.new_name()
导致此错误:

TypeError: __init__() missing 1 required positional argument: 'self'

为什么这不起作用?我应该如何正确地别名

__init__

python python-3.x methods alias
1个回答
0
投票

__init__
方法有别名。但
__init__
并不是一个构造函数。

你可能会这样做:

MyClass.new_name = MyClass.__call__

如果你想让事情“顺利进行”。但这在我看来相当奇怪。只需定义一个

classmethod

© www.soinside.com 2019 - 2024. All rights reserved.