Python中的构造函数
先决条件: Python中的面向对象编程、 Python中的面向对象编程 |设置 2
构造函数通常用于实例化对象。构造函数的任务是在创建类的对象时对类的数据成员进行初始化(赋值)。在Python中,__init__() 方法称为构造函数,并且总是在创建对象时调用。
构造函数声明的语法:
def __init__(self):
# body of the constructor
构造函数的类型:
- 默认构造函数:默认构造函数是一个不接受任何参数的简单构造函数。它的定义只有一个参数,即对正在构造的实例的引用。
- 参数化构造函数:带参数的构造函数称为参数化构造函数。参数化构造函数将其第一个参数作为对正在构造的实例的引用,称为 self,其余参数由程序员提供。
默认构造函数示例:
Python3
class GeekforGeeks:
# default constructor
def __init__(self):
self.geek = "GeekforGeeks"
# a method for printing data members
def print_Geek(self):
print(self.geek)
# creating object of the class
obj = GeekforGeeks()
# calling the instance method using the object obj
obj.print_Geek()
Python3
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
# creating object of the class
# this will invoke parameterized constructor
obj = Addition(1000, 2000)
# perform Addition
obj.calculate()
# display result
obj.display()
输出 :
GeekforGeeks
参数化构造函数的示例:
Python3
class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
# creating object of the class
# this will invoke parameterized constructor
obj = Addition(1000, 2000)
# perform Addition
obj.calculate()
# display result
obj.display()
输出 :
First number = 1000
Second number = 2000
Addition of two numbers = 3000