易百教程

10、如何在 Python 中重载构造函数或方法?

Python的构造函数:_init__()是一个类的第一个方法。每当尝试实例化一个对象时,python 会自动调用 __init__() 来初始化对象的成员。不能在 Python 中重载构造函数或方法。 如果尝试重载此方法,它会显示错误。

代码例子:

class student:    
    def __init__(self, name):    
        self.name = name    
    def __init__(self, name, email):    
        self.name = name    
        self.email = email    

# This line will generate an error    
#st = student("yiibai")    

# This line will call the second constructor    
st = student("yiibai", "yiibai@gmail.com")    
print("Name: ", st.name)  
print("Email Address: ", st.email)

运行结果:

Name:  yiibai
Email Address:  yiibai@gmail.com