了解DelphiVCL的__init__,用于Windows应用开发

198 阅读2分钟

每当在Python中进行面向对象编程时,我们大多会遇到 __init__ 方法。这篇文章解释了Python中__init__方法的主要概念,当用于Windows应用程序的图形用户界面(GUI)开发时。

"__init__"Python类中的一个保留方法。它在面向对象的概念中被称为构造函数。当一个对象从类中被创建时,这个方法被调用,它允许类初始化类的属性。

__init__方法类似于C++和Java中的构造函数。构造器用于初始化对象的状态。构造函数的任务是当一个类的对象被创建时,对该类的数据成员进行初始化(赋值)。像方法一样,构造函数也包含了在对象创建时执行的语句(即指令)的集合。一旦一个类的对象被实例化,它就被运行。该方法对于做任何你想对你的对象进行的初始化是很有用的。

下面是我们如何使用__init__的基本例子。

# A Sample class with __init__ method
class Person:  
    # init method or constructor   
    def __init__(self, name):  
        self.name = name  
      
    # Sample Method   
    def say_hi(self):  
        print('Hello, my name is', self.name)  
      
p = Person('Jim')  
p.say_hi()

PyScripter IDE中的输出。

output1-2981122

在上面的例子中,一个名为Jim的人被创建。在创建一个人的时候,"Jim "被作为一个参数传递,这个参数将被传递给__init__方法来初始化这个对象。关键字self代表一个类的实例,并将属性与给定的参数绑定。同样地,通过传递不同的名字作为参数,可以创建许多Person类的对象。下面是这个例子。

# A Sample class with init method
class Person:
    # init method or constructor
    def __init__(self, name):
        self.name = name

    # Sample Method
    def say_hi(self):
        print('Hello, my name is', self.name)

# Creating different objects
p1 = Person('Jim')
p2 = Person('Eli')
p3 = Person('Marco')

p1.say_hi()
p2.say_hi()
p3.say_hi()

PyScripter IDE中的输出。

output2-7735754

下面的代码是在使用DelphiVCL库创建GUI的背景下使用__init__方法的工作实例。

from DelphiVCL import *

class MainForm(Form):
    def __init__(self, Owner):
        self.Caption = "A VCL Form..."
        self.SetBounds(10, 10, 340, 410)
        self.lblHello = Label(self)
        self.lblHello.SetProps(Parent=self, Caption="Hello Python")
        self.lblHello.SetBounds(10,10,100,24)
        self.edit1 = Edit(self)
        self.edit1.SetProps(Parent=self, Top=30, Left=10, Width=200, Height=24)
        self.button1 = Button(self)
        self.button1.SetProps(Parent=self, Caption="Add", OnClick=self.Button1Click)
        self.button1.SetBounds(220,29,90,24)
        self.lb1 = ListBox(self)
        self.lb1.SetProps(Parent=self)
        self.lb1.SetBounds(10,60,300,300)
        
    def Button1Click(self, Sender):
        self.lb1.Items.Add(self.edit1.Text)

def main():
    Application.Initialize()
    Application.Title = "My DelphiVCL App"
    f = MainForm(Application)
    f.Show()
    FreeConsole()
    Application.Run()
main()

这里是GUI的结果。

1_1-9827765