【问题标题】:Is it possible to change the constructor method (__init__) name to something else in python?是否可以将构造函数方法(__init__)名称更改为python中的其他名称?
【发布时间】:2020-10-07 18:23:40
【问题描述】:

我们可以在 python 中将构造函数方法 (__init__) 名称更改为其他名称吗? 例子

class Employee:

    num_of_emps = 0
    raise_amt = 1.04

    def __newconstructorname__(self, first, last, pay):
        self.first = first
        self.last = last
        self.email = first + '.' + last + '@email.com'
        self.pay = pay

【问题讨论】:

  • 为什么需要这样做?
  • 你可以通过定义一个自定义元类来做到这一点。
  • 定义一个函数并将其命名为您喜欢的任何名称,然后从__init__() 调用它。我认为这是您将获得的最接近的结果,除非您真的知道自己在做什么。

标签: python oop constructor init


【解决方案1】:

最简单的可能是重新分配它,但正如@Barmar 所问:“你为什么要这样做?”:

class Employee:

    num_of_emps = 0
    raise_amt = 1.04

    def __newconstructorname__(self, first, last, pay):
        print('in init')
        self.first = first
        self.last = last
        self.email = first + '.' + last + '@email.com'
        self.pay = pay

    __init__ = __newconstructorname__

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 2012-08-23
    • 1970-01-01
    • 2016-03-05
    • 2021-02-25
    • 1970-01-01
    • 2015-04-13
    • 2012-07-03
    • 2021-12-05
    相关资源
    最近更新 更多