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 color in not_self_but_still_self.colors_available
# 创建类的实例
laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black'])
# 调用不带 color 关键字的 is_laptop_available 方法
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 程序员都遵循的标准
结论
如果您对本教程有任何疑问,请在评论部分中提及。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

