首页 > 解决方案 > python用字典和打印实例化类

问题描述

  1. 为什么print(obj_1.dic['a'].print_1())给我的行 output = " hello_from_x \n None" ?实际上我对“ None”感到困惑
  2. 该行是否'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())

'

标签: pythonoop

解决方案


因为您的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())

你会得到输出**


推荐阅读