[英]Is there a way to call a method on a Python object returned by a function?
[英]python - returning the type of an object function / method call
我解决了这样一个问题,我遇到了一个问题。
下面是这句话的内容:使用命令“type”检查function(打印)返回的object的类型和方法-hello class 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 class 的 Hello 方法返回的 object 的类型。
使用以下命令:
print (type(p.hello()))
然而,这个命令什么也不返回——我不知道它是否能很好地完成这项工作。 我想寻求帮助/建议。
我提前感谢您的每一个答案!
我相信这就是您要实现的目标
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()))
无论您在 function 中创建了什么,并且想要在外部访问它,都必须返回它
在检查其类型之前,您应该有一个返回值,例如SP_ 的 answer 。 只想补充一点,如果您要检查某些 if-else 子句中的数据类型,那么isinstance()是比使用type()
比较其类型更好的选择。 喜欢:
p = Person()
if isinstance(p, Person):
print("do something")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.