Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python类中打印输出_Python_Class - Fatal编程技术网

如何在python类中打印输出

如何在python类中打印输出,python,class,Python,Class,我想弄明白,但我是斯图克。我有这个脚本 class Myname(): def first_name(self): print("it's Mark") def last_name(self): print ("it's Anthony") class Myself(): def speak(self): print ("I'm Speaking") def __init__(self):

我想弄明白,但我是斯图克。我有这个脚本

 class Myname():
     def first_name(self):
         print("it's Mark")
     def last_name(self):
         print ("it's Anthony")

 class Myself():
     def speak(self):
         print ("I'm Speaking")
     def __init__(self):
         self.speak = Myname()
     def say(self,word):
         print (word)


 me = Myself()

 me.speak.first_name()
该脚本显示:

it's Mark
但当我说:

me.speak()
然后发生这种情况

TypeError: 'Myname' object is not callable

有什么解决方案吗?

您使用了两次
speak
,一个函数定义和一个属性。当你说
me.speak()
时,它试图调用不可调用的属性

重命名其中一个:

def speak2(self):
    print ("I'm Speaking")
然后用新名字称呼它:

me.speak2()
删除类中的speak()方法

代码(在python shell中):

执行输出:

    >>> me = Myself()
    >>>
    >>> me.speak.first_name()
    it's Mark
    >>>
me.speak.first\u name()
不会删除
speak()
,因为当你说
me.speak.first\u name()
时,它不会调用
speak
,而是使用它。OP想使用
me.speak()
    >>> me = Myself()
    >>>
    >>> me.speak.first_name()
    it's Mark
    >>>