English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico do Python

Controle de Fluxo do Python

Funções do Python

Tipos de Dados do Python

Operações de Arquivos do Python

Objetos e Classes do Python

Data e Hora do Python

Conhecimento Avançado do Python

Manual de Referência do Python

Uso e exemplo do int() no Python

Python built-in functions

O método int() retorna um objeto inteiro a partir de qualquer número ou string.

A sintaxe do método int() é:

int(x=0, base=10)

Parâmetros do int()

O método int() aceita dois parâmetros:

  • x-o número ou a string que deve ser convertido para um objeto inteiro.
    parâmetro padrãoé zero.

  • base-em xa base do número.
    Pode ser 0 (literal de código) ou2-36.

O valor retornado pelo int()

O método int() retorna:

  • Dado um número ou um objeto inteiro em uma string, considera o valor padrão como10

  • (sem parâmetros) retorna 0

  • (if a base is specified) then with the specified base (0,}2,8,10,16String handling

Example1How does int() work in Python?

# Integer
print('int(123) is:123))
# Float
print('int(123int(23) is:123int(23))
# String
print('int('123) is:123))

When running the program, the output is:

)) is:123. 123
)) is:123int(23. 123
) is:123 123

Example2

1010, int is:1010, 2))
1010, int is:1010, 2))
# Octal 0o or 0O
12, int is:12, 8))
12, int is:12, 8))
# Hexadecimal
print('For A, int is:', int('A', 16))
print('For 0xA, int is:', int('0xA', 16))

When running the program, the output is:

For1010, int is: 10
For 0b1010, int is: 10
For12, int is: 10
For 0o12, int is: 10
For A, int is: 10
For 0xA, int is: 10

Example3Custom object int()

Internally, the int() method calls the __int__() method of the object.

Therefore, even if an object is not a number, it can be converted to an integer object.

You can return a number by overriding the __index__() and __int__() methods of the class.

These two methods should return the same value because old versions of Python used __int__() and newer Python uses __index__() method.

class Person:
    age = 23
    def __index__(self):
        return self.age
    
    def __int__(self):
        return self.age
person = Person()
print('int(person) is:', int(person))

When running the program, the output is:

int(person) is: 23

Python built-in functions