每当在Python中进行面向对象的编程时,那么我们就会经常遇到self方法作为其第一个参数。这篇文章解释了Windows开发中Python的self方法的主要概念。
self代表Python中类的实例。通过使用**"self "关键字,我们可以访问Python中类的属性和方法**。它将属性与给定的参数结合起来。
你需要使用self的原因是Python不使用@语法来引用实例的属性。Python决定用一种方式来做方法,使方法所属的实例被自动传递,但不是自动接收。方法的第一个参数是方法所调用的实例。
下面是我们如何使用self关键字的基本例子。
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Meow")
Cat("Kitty", "4").info()
Cat("Kitty", "4").make_sound()
PyScripter IDE中的输出。

下面是另一个例子。
class car():
# __init__ method or constructor
def __init__(self, model, color):
self.model = model
self.color = color
def show(self):
print("Model is", self.model )
print("color is", self.color )
# Both objects have different self which contain their attributes
audi = car("audi a4", "blue")
ferrari = car("ferrari 488", "green")
# Same output as car.show(audi)
audi.show()
# Same output as car.show(ferrari)
ferrari.show()
# Behind the scene, in every instance method call, Python sends the instances also with that method call like car.show(audi)
PyScripter IDE中的输出。

注意: self是一个惯例,而不是一个真正的Python关键字。self是函数中的一个参数,用户可以使用另一个参数名来代替它。但是,建议使用self来增加代码的可读性。
下面的代码是在使用DelphiVCL库创建GUI的情况下使用self参数的工作实例。
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的结果。

你可以在这里浏览更复杂的演示。