如果您使用的是Python,那么“自我”这个词是无法逃避的。它用于方法定义和变量初始化。每次我们定义方法时,都会明确使用Self方法。在本文中,我们将按以下顺序深入了解Python中的自我深度:
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类自构造函数
class Person:
# name made in constructor
def __init__(self, John):
self.name = John
def get_person_name(self):
return self.name
Self还

本文探讨了Python中的self关键字,它用于表示类的实例,访问类的属性和方法,且在自构造函数中引用类的变量字段。尽管self常被视为关键字,但实际上在Python中它并非如此,而是一个约定俗成的参数名,用于提高代码可读性。
最低0.47元/天 解锁文章
1477

被折叠的 条评论
为什么被折叠?



