0

Just trying to figure out what the difference is between .type() method and type() function. To me, I don't see why they are returning different outputs although they seem to be doing the same thing (ie. determining the type of the object)

x = 1
print(x.type())

returns: AttributeError: 'int' object has no attribute 'type'

whereas

x = 1
print(type(x))

returns: <class 'int'>

Anyone have any ideas?

1
  • 1
    the difference is - one exists and returns type of object - another does not exist - what basically error message tells to you... Commented Jul 10, 2020 at 5:47

3 Answers 3

4

There is no such thing as a .type() method for int. That is what the first message is saying. So use the second version and you are fine.

Sign up to request clarification or add additional context in comments.

Comments

1

type() is a built-in function, which returns the type of the object you pass in as the parameter.


When you try to call x.type(), what you're attempting to do is call the type() method on an int object, and that simply does not exist. Hence the attribute error.
Note, to check the attributes that actually exist for x, you could use dir(x)

Comments

0

The type(object) function returns the class an object is an instance of. For example, type(42) tells you that 42 is an int.

If you were to make a custom class, using type(object) where object is an instance of the new class would return the class itself.

You can also look into using the isinstance function, which is widely considered to be more Pythonic.

The .type() method doesn’t exist, at lease not for ints. That’s why you get an error there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.