在本教程中,我们要了解自己的Python的。如果您正在使用Python,则必须熟悉它。我们将看到一些有趣的事情。
注意-self不是Python中的关键字。
让我们从Python中最常用的self入手。
我们将在类中使用self来表示对象的实例。我们可以创建一个类的多个,并且每个实例将具有不同的值。和自我帮助我们的类的实例中获得这些属性值。让我们看一个小例子。
# class class Laptop: # init method def __init__(self, company, model): # self self.company = company self.model = model
我们将类的属性定义为self。[something]。因此,每当我们创建该类的实例时,其自身都将引用一个与我们正在访问类属性或方法的实例不同的实例。
现在,让我们创建类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
我们已经改变了名称自到别的东西。但是仍然可以像以前一样工作。没有区别。因此,自我不是关键字。而且,我们可以将自我改变为我们想要拥有的一切。这更像一个参数。
注意-最佳实践是使用自我。。这是每个Python程序员都遵循的标准
如果您对本教程有任何疑问,请在评论部分中提及。