【发布时间】:2020-03-31 11:42:22
【问题描述】:
在下面的代码中,
# An example class with some variable and a method
class ExampleClass(object):
def __init__(self):
self.var = 10
def dummyPrint(self):
print ('Hello World!')
# Creating instance and printing the init variable
inst_a = ExampleClass()
# This prints --> __init__ variable = 10
print ('__init__ variable = %d' %(inst_a.var))
# This prints --> Hello World!
inst_a.dummyPrint()
# Creating a new attribute and printing it.
# This prints --> New variable = 20
inst_a.new_var = 20
print ('New variable = %d' %(inst_a.new_var))
# Trying to create new method, which will give error
inst_a.newDummyPrint()
我可以在类之外创建一个新的属性 (new_var),使用实例。它有效。理想情况下,我期待它不会起作用。
同样我尝试创建新的方法 (newDummyPrint());这将打印 AttributeError: 'ExampleClass' object has no attribute 'newDummyPrint' 正如我所料。
我的问题是,
- 为什么创建新属性会起作用?
- 为什么创建新方法不起作用?
【问题讨论】:
-
inst_a.new_var = ...将值分配给(新)属性。inst_a.newDummyPrint()不是“创建”一个新方法,它只是试图调用一个。 -
您实际上并没有在任何地方创建
inst_a.newDummyPrint。你只是直接跳起来试图打电话给它。如果您在没有先设置值的情况下直接尝试读取inst_a.new_var,您会遇到同样的错误。