python - python用字典和打印实例化类
问题描述
- 为什么
print(obj_1.dic['a'].print_1())
给我的行 output = "hello_from_x \n None
" ?实际上我对“None
”感到困惑 - 该行是否
'a':x()
等效于 a = x() #instantiate ?
'
class x:
def print_1(self):
print("hello_from_x")
class y:
def print_1(self):
print("hello_from_y")
class z:
dic = {'a':x(), 'b':y()}
obj_1 = z()
obj_1.dic['a'].print_1()
print(obj_1.dic['a'].print_1())
'
解决方案
因为您的print_1()
函数不返回任何内容,所以您得到的输出为None
如果你这样做:
class x:
def print_1(self):
print("hello_from_x")
return "**"
class y:
def print_1(self):
print("hello_from_y")
class z:
dic = {'a':x(), 'b':y()}
obj_1 = z()
obj_1.dic['a'].print_1()
print(obj_1.dic['a'].print_1())
你会得到输出**
推荐阅读
- c++ - 编写一个程序,将一行文本作为输入,并反向输出该行文本。C++
- python - 用python循环成绩平均函数
- javascript - JS - 如何使用接受多个参数的函数删除事件侦听器?
- ios - 选择单元格后,如何向集合视图单元格添加约束?
- java - 如果我们在 java 线程完成任务之前关闭它(返回),Activity 就会崩溃
- floating-point - 如果我们将格式更改为类似于双 IEEE 754-1985 的格式,我们能否消除数字的浮点错误?
- apache-kafka - 使用 Kafka 主题向 Storm Crawler 提供种子 URL
- java - 具有多个方法调用的类的 JUnit 测试
- javascript - 无法在“弹出”中找到元素
- java - 如何在 TimerListener 内使用简单循环正确移动形状?