在python中,每个类都有一个构造函数,它是类内部指定的特殊方法。构造函数/初始化程序将在为类创建新对象时自动调用。当对象被初始化时,构造函数将值分配给类中的数据成员。
没有必要显式定义构造函数。但为了创建构造函数,我们需要遵循以下规则 -
对于一个类,它只允许有一个构造函数。
构造函数名称必须是 __init__。
必须使用实例属性定义构造函数(只需将 self 关键字指定为第一个参数)。
它不能返回除 none 之外的任何值。
语法class a(): def __init__(self): pass
示例考虑下面的示例并了解构造函数的工作原理。
class sampleclass(): def __init__(self): print(it a sample class constructor)# creating an object of the class a = sampleclass()
输出it a sample class constructor
在上面的块中,为 sampleclass() 创建了对象 a,并且对于此实例,会自动执行方法 __init__(self)。这样它就显示了构造函数的语句。
构造函数分为三种类型。
默认构造函数
参数化构造函数
非参数化构造函数
默认构造函数默认构造函数不是由用户定义的,python 本身在程序编译期间创建了一个构造函数。它不执行任何任务,但初始化对象。
示例python 生成一个空构造函数,其中没有任何代码。请参阅下面的示例。
class a(): check_value = 1000 # a method def value(self): print(self.check_value)# creating an object of the classobj = a()# calling the instance method using the objectobj.value()
输出1000
让我们使用python内置的dir()函数来验证类a的构造函数。
dir(a)output:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'check_value', 'value']
python dir() 函数返回指定对象的所有属性和方法的列表。在上面的列表中我们可以看到为对象 a 创建了默认构造函数 __init__ 。
参数化构造函数参数化构造函数接受一个或多个参数以及 self。当您想要创建一个具有自定义属性值的对象时,它非常有用。参数化构造函数允许我们在创建对象时指定对象属性的值。
示例让我们看一个带有参数化构造函数的类的示例
class family: members = 10 def __init__(self, count): self.members = count def disply(self): print(number of members is, self.members) joy_family = family(25)joy_family.disply()
输出number of members is 25
这里使用自定义值 25 创建对象 joy 系列,而不是使用默认成员属性值 10。并且该值可以用于此实例,因为它被分配给 self.members 属性。
非参数化构造函数非参数化构造函数不接受除 self 之外的任何参数。当您想要操作实例属性的值时,它非常有用。
示例让我们看一个非参数化构造函数的示例。
class player: def __init__(self): self.position = 0 # add a move() method with steps parameter def move(self, steps): self.position = steps print(self.position) def result(self): print(self.position)player1 = player()print('player1 results')player1.move(2)player1.result()print('p2 results')p2 = player()p2.result()
输出player1 results22p2 results0
player1 对象通过使用 move() 方法来操作“position”属性。并且 p2 对象访问“position”属性的默认值。
以上就是python中的构造函数的详细内容。