简体   繁体   中英

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.

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.

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

You should have a return value before checking its type, like SP_'s 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() . Like:

p = Person()

if isinstance(p, Person):
    print("do something")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM