Python中的构造函数用法快速指南

2021年3月27日13:58:18 发表评论 1,372 次浏览

Python构造函数通常用于实例化对象。构造函数的任务是在创建类的对象时初始化(分配值)给类的数据成员。在Python中, __init __()方法称为构造函数, 并且始终被称为创建对象时。

构造函数声明的语法:

def __init__(self):
    # body of the constructor

构造函数的类型:

默认构造函数的示例:

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()

输出:

GeekforGeeks

参数化构造函数的示例:

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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: