从对象内打印

2024-03-29 01:49:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让一个python对象继承另一个。我写了一个脚本来测试正在工作的东西(见下文)。然而,当我试图访问这些对象中的方法时,什么都不会被打印出来,我也不明白为什么。有人能给我指出正确的方向吗

print("hello world")

class parent():
    def helloWorld(self, ):
        print("hello World1")

class child(parent):
    def helloWorld2(self, ):
        print("hello World2")

parentOBJ = parent()
childOBJ = child()


parentOBJ.helloWorld
childOBJ.helloWorld
childOBJ.helloWorld2

上面的代码打印第一个“helloworld”语句,但之后什么也没有


Tags: 对象方法self脚本childhellodefclass
2条回答

你没有调用方法。当您要调用每个方法时,在它们后面添加()。否则,解释器将只返回对象的类型

parentOBJ.helloWorld()
childOBJ.helloWorld()
childOBJ.helloWorld2()

但是,您还必须修复类定义:

class parent(object): # All classes should inherit from the object-class
    def helloWorld(self): # unless you have other arguments besides self, remove the comma.
        print("hello World1")

class child(parent):
    def helloWorld2(self):
        print("hello World2")

示例:

>>> parentOBJ = parent()
>>> childOBJ = child()
>>> parentOBJ.helloWorld()
hello World1
>>> childOBJ.helloWorld()
hello World1
>>> childOBJ.helloWorld2()
hello World2

您只是引用了这些方法,实际上并没有调用它们

请改为:

parentOBJ.helloWorld()
childOBJ.helloWorld()
childOBJ.helloWorld2()

调用函数时,必须执行method_name(arguments)

因此,如果我有一个名为def hello(a, b):的方法,我实际上也需要将参数传递给函数,如下:hello('hello', 'world')

示例

>>> def hello(): 
...     print 'hello' 
...  
>>> hello
<function hello at 0x2340bc>
>>> hello()
hello

希望有帮助

相关问题 更多 >