2

As I understand there are no declaration types in Python. When you need an integer or list you would do:

integer = 5
list_of_integers = [0, 1, 2]

This link to the documentation tells me that int in Python is a built-in function.

I'm aware of functions such as str() and int() to convert an integer to string and vice-versa.

But I have never seen a use of int as a type with dot notation E.g. *int.[function_name]*

How come it can be both a type and a function with the same name? Are there other types such as float, double, and etc. which can be used with dot notation and as well as a function?

1
  • There are actually some methods that you can call on integers, i.e. (15).bit_length() returns 4. The parentheses are needed for the parser. Commented Apr 8, 2014 at 8:50

2 Answers 2

4

int and str are classes. As with any class in Python, calling it gives you an instance. And as with any instance, you certainly can call methods on it. int doesn't have that many user-callable methods, but str certainly does: some of the common ones include strip, split, upper, etc.

>>> x = str()
>>> x.upper()
''

Edit

It's still a class. You can do exactly the same with any class, even ones you define yourself:

>>> class Foo(object):
...   def bar(self):
...     print self.baz
...
>>> f=Foo()
>>> f.baz = 'quux'
>>> f.bar()
quux
>>> Foo.bar(f)
quux

The last operation here is exactly the same idea as calling str.upper(x)

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

3 Comments

ints do have user accessible attributes, but they're not always very useful and mostly there so that int fits in its proper place in the numeric tower. eg, because integers are rational, they have a numerator and denominator; because they're complex, they have real and imaginary parts. They also have the conjugate() method, again a complex thing. More usefully but less obviously, all comparison and arithmetic operators and the functions round, divmod, floor, ceil and trunc call __-methods.
Sure, that's why I said "not that many", not "none". But thanks for the clarification.
It is possible to write str.upper(x) Is str an object of type str or is it still a class here?
0

int and str aren't functions. They are basically data types which in python are actually classes containing different functions of their own. That's why you can convert an integer to a string using the str(int) method but you can't do the same with int(string) to convert a string to an integer. And as these are classes one can say that there are different functions (methods) in the class which are in turn use with the dot notation.

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.