python - 使用类名和点运算符调用方法
问题描述
当我们在类中定义一个方法并尝试使用 class_name.method_name 访问该方法时,它会显示一个错误,要求为“self”提供参数。例如 prgm 如下:
class a:
def b(self):
print('method b')
def c(self):
print('method c')
a.b() #self.b()
d=a()
d.c()
a.c() #d.c()
在方法b内部和类外部,如果我使用类名a调用方法b,即ac(),它会显示错误如下:
TypeError : b() missing 1 required positional argument: 'self'
你能解释一下为什么它需要一个“self”的参数,尽管当我们使用对象调用它时我们不需要指定?
解决方案
当使用对象调用方法时,self
参数会自动作为调用对象传递。
当您使用 调用它时class
,python 无法了解调用对象是谁,因此,self
参数保持为空。
class Foo:
def bar(self):
pass
f = Foo()
f.bar()
# or
Foo.bar(f) # explicitly pass f to the self parameter for it to work
推荐阅读
- c# - Configuration.GetSection("ConnectionStringName").Get始终为空
- ms-access - MS Access - 登录
- mysql - 重写一个嵌套的mysql查询以创建一个视图
- sas - 在满足条件之前,不同数量的观察的平均值/计数
- c# - 已发布网站:尝试为文件附加自动命名数据库...失败
- java - Java中LinkedList类中的iterator()方法在哪里?
- dialogflow-es - 对话流中意图的输入/输出上下文
- prestashop - Blocklayered模块不工作prestashop 1.6
- angular - 当我导航到另一个组件时,如何使第一个组件的变量不被删除
- internet-explorer - Angular 5 在 IE11 中不起作用:无法获取 null 或未定义引用的“调用”属性