Python中的Self

Python中的Self

Python中的Self

  如果你正在使用Python,就无法逃避“ self ”这个词。它用于方法定义和变量初始化。每次我们定义一个方法时,都会显式地使用 self 方法。在本文中,我们晓得博客将为你介绍Python中的Self有什么用。

  推荐:通过Python使用ChatGPT

Python中的Self有什么用

Python中的Self有什么用

  self 用于表示类的实例。有了这个关键字,就可以在 python 中访问类的属性和方法。它使用给定的参数绑定属性。我们使用 self 的原因是 Python 不使用 ‘ @ ‘ 语法来引用实例属性。在 Python 中,我们有一些方法可以使实例自动传递,但不会自动接收。

class food():
 
# init method or constructor
    def __init__(self, fruit, color):
        self.fruit = fruit
        self.color = color
 
    def show(self):
        print("fruit is", self.fruit)
        print("color is", self.color )
 
apple = food("apple", "red")
grapes = food("grapes", "green")
 
apple.show()
grapes.show()

输出:
Fruit is apple
color is red
Fruit is grapes
color is green

  推荐:如何在Python中反转字符串

Python类自构造函数

  self 也用于引用类中的变量字段。让我们举个例子,看看它是如何工作的:  

class Person:
 
# name made in constructor
def __init__(self, John):
self.name = John
 
def get_person_name(self):
return self.name

  在上面的例子中,self 指的是整个 Person 类的 name 变量。在这里,如果我们在方法中有一个变量,self 将不起作用。该变量仅在该方法运行时才存在,因此是该方法的本地变量。为了定义全局字段或整个类的变量,我们需要在类方法之外定义它们。

  推荐:如何使用Python程序Pytube库下载YouTube视频

self 是关键字吗?

self是关键字吗

  self 在不同的地方使用,通常被认为是关键字。但与 C++不同的是,self 在 Python 中不是关键字。self 是函数中的参数,用户可以使用不同的参数名称代替它。虽然建议使用 self,因为它增加了代码的可读性。

class this_is_class:
def show(in_place_of_self):
print("It is not a keyword "
"and you can use a different keyword")
 
object = this_is_class()
object.show()

输出:
It is not a keyword and you can use a different keyword

  推荐:Python Global Keyword全局关键字

总结

  以上是晓得博客将为你介绍Python中的 Self 有什么用的全部内容,至此文章结束了,希望您了解 self 的用法以及它在 Python 中的工作方式,如有问题,欢迎联系我们。

  推荐:零基础如何开始学习Python


晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python中的Self

转载请保留链接:https://www.pythonthree.com/python-self/

滚动至顶部