Python 类中的 self
在本教程中,我们将学习 Python 中的 self。如果您使用 Python,那么您一定熟悉它。我们将了解一些关于它的有趣之处。
注意 - self 在 Python 中不是关键字。
让我们从 Python 中 self 最常见的用法开始。
我们将在类中使用 self 来表示对象的实例。我们可以创建多个类的实例,并且每个实例都将具有不同的值。而 self 帮助我们在类实例中获取这些属性值。让我们来看一个例子。
示例
# class class Laptop: # init method def __init__(self, company, model): # self self.company = company self.model = model
我们将类的属性定义为 self.[something]。因此,每当我们创建一个 类 的实例时,self 将引用一个不同的实例,我们从中访问类属性或方法。
现在,让我们创建两个 Laptop 类的实例,看看 self 如何工作。
示例
# class
class Laptop:
# init method
def __init__(self, company, model):
# self
self.company = company
self.model = model
# creating instances for the class Laptop
laptop_one = Laptop('Lenovo', 'ideapad320')
laptop_two = Laptop('Dell', 'inspiron 7000')
# printing the properties of the instances
print(f"Laptop One: {laptop_one.company}")
print(f"Laptop Two: {laptop_two.company}")输出
如果您运行上述代码,则将得到以下结果。
Laptop One: Lenovo Laptop Two: Dell
我们为同一个属性得到了两个不同的名称。让我们看看其背后的细节。
Python 在访问其方法时默认会发送对实例的引用,而该引用被捕获在 self 中。因此,对于每个实例,引用都是不同的。我们将获得相应的实例属性。
我们知道 self 不是 Python 的关键字。它更像是一个参数,在访问实例的任何属性或方法时,您不需要发送它。
Python 将自动为您发送对实例的引用。我们可以使用任何变量名来捕获实例的引用。运行以下代码并查看输出。
示例
import inspect
# class
class Laptop:
# init method
def __init__(other_than_self, company, model, colors):
# self not really
other_than_self.company = company
other_than_self.model = model
other_than_self.colors_available = colors
# method
def is_laptop_available(not_self_but_still_self, color):
# return whether a laptop in specified color is available or not
return color in not_self_but_still_self.colors_available
# creating an instance to the class
laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black'])
# invoking the is_laptop_available method withour color keyword
print("Available") if laptop.is_laptop_available('Silver') else print("Not available")
print("Available") if laptop.is_laptop_available('White') else print("Not available")输出
如果您运行上述代码,则将得到以下结果。
Available Not available
我们将名称 self 更改为 其他名称。但是,它仍然像以前一样工作。没有区别。因此,self 不是关键字。此外,我们可以将 self 更改为我们喜欢的任何名称。它更像是一个参数。
注意 - 最佳实践是使用 self.。这是每个 Python 程序员都遵循的标准。
结论
如果您在本教程中有任何疑问,请在评论部分提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP