[英]python - returning the type of an object function / method call
I solve such a problem and I ran into a problem.我解决了这样一个问题,我遇到了一个问题。
Here is the content of the sentence: Using the command "type" check the type of the object returned by the function (print) and the method-hello the class Person.下面是这句话的内容:使用命令“type”检查function(打印)返回的object的类型和方法-hello class Person。
here is the code I have written so far:这是我到目前为止编写的代码:
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()
and I would like to check the type of the object returned by the Hello method of Person class.我想检查 Person class 的 Hello 方法返回的 object 的类型。
using the following command:使用以下命令:
print (type(p.hello()))
however, this command returns nothing - I don't know if it does the job well.然而,这个命令什么也不返回——我不知道它是否能很好地完成这项工作。 I would like to ask for help / advice.
我想寻求帮助/建议。
I thank you in advance for every answer!我提前感谢您的每一个答案!
I believe this is what you are trying to achieve我相信这就是您要实现的目标
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()))
Whatever that you created inside the function and want to access it outside you must return it无论您在 function 中创建了什么,并且想要在外部访问它,都必须返回它
You should have a return value before checking its type, like SP_'s answer .在检查其类型之前,您应该有一个返回值,例如SP_ 的 answer 。 Just want to add that if you're going to check the data type in some if-else clauses, then isinstance() is a better option than comparing its type using
type()
.只想补充一点,如果您要检查某些 if-else 子句中的数据类型,那么isinstance()是比使用
type()
比较其类型更好的选择。 Like:喜欢:
p = Person()
if isinstance(p, Person):
print("do something")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.