首页 > 解决方案 > python - 返回对象函数/方法调用的类型

问题描述

我解决了这样一个问题,我遇到了一个问题。

下面是这句话的内容:使用命令“type”检查函数返回的对象的类型(print)和方法-hello类Person。

这是我到目前为止编写的代码:

class Person:
    def __init__(self, name="John", surname="Douglas"):
        self.name= name
        self.surname= surname

        def hello(self):
            print("Hello" + self.name + " " + self.surname)

            Person.hello= "text"
            p = Person()
            p.hello()

我想检查 Person 类的 Hello 方法返回的对象的类型。

使用以下命令:

print (type(p.hello()))

但是,这个命令什么也不返回——我不知道它是否能很好地完成这项工作。我想寻求帮助/建议。

我提前感谢您的每一个答案!

标签: pythonclassobjectinheritanceprinting

解决方案


我相信这就是您要实现的目标

class Person:
    def __init__(self, name="John", surname="Douglas"):
        self.name= name
        self.surname= surname

    def hello(self):
        

        #return the string 
        return "Hello " + self.name + " " + self.surname
            
        #Person.hello= "text"
        
#instantiate class Person outside the class
p = Person()
            #p.hello()

print(type(p.hello()))

无论您在函数内部创建什么并希望在外部访问它,都必须返回它


推荐阅读