首页 > 解决方案 > 在开始的python构造函数中“self”这个词有什么用?

问题描述

你好所以这是我第一次学习python,我遇到了构造函数。有人可以告诉我为什么我们需要“自我”这个词。这是代码:def init(self,n,p,i,):

标签: pythonconstructor

解决方案


构造函数中的单词“self”表示类的实例。使用这个关键字,我们可以访问类中的变量和函数。例如:

class foo:
    '''Just an example'''

    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age
    
    def fun(self):
        ''' We include the word "self" inside the function as an object to invoke the 
            fun() inside the class.'''
        print("Name: {}".format(self.name))
        print("Age : {}".format(self.age))

    def display(self):
         ''' To display the name and age.'''
         self.fun()

class_object = foo("John Doe", 30)
# The word 'self' isn't required when calling the function outside the class.   
class_object.display()
# Name: John Doe
# Age : 30 

这并不意味着“self”这个词是 python 中的保留关键字。我们可以使用任何其他词来表示类的实例。例如:

class foo:
    '''Just an example again'''
   
    def __init__(fun, person_name, person_age):
        fun.name = person_name
        fun.age = person_age     

    def display(fun):
        print("Name: {}".format(fun.name))
        print("Age : {}".format(fun.age))

class_object = foo("John Doe", 30)
class_object.display()
# Name: John Doe
# Age : 30 
        

推荐阅读