python - 在开始的python构造函数中“self”这个词有什么用?
问题描述
你好所以这是我第一次学习python,我遇到了构造函数。有人可以告诉我为什么我们需要“自我”这个词。这是代码:def init(self,n,p,i,):
解决方案
构造函数中的单词“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
推荐阅读
- c# - Prism MVVM ObservesCanExecute - 我如何嵌套(逻辑与)简单的可观察属性
- mysql - 过滤所有行的特定条件,并为每列返回具有相同值的一行
- django - Django 网站部署引发了一个 ImproperlyConfigured 错误
- mysql - 在 MySQL 文档中哪里可以找到 const 的解释
- javascript - 尝试在firebase中链接多个身份验证提供程序时从error.email获取“未定义”
- flutter - 在同一个项目中获取多个 Flutter 应用
- angular - 在数组类型的 RxJS 主题上调用 .next() 不会通知观察者
- python - 如何在python中打开json文件
- java - 遇到 OutOfMemoryException 时删除 List<> 的一部分
- android - 如何在 as3 上实现运行时权限?