Найти - Пользователи
Полная версия: Проверка типа переменных
Начало » Python для новичков » Проверка типа переменных
1 2
MetalHead
Доброго вечера, товарищи. Не пойму как проверить типы переменных. Просвятите пожалуйста.
class Plus_to_price:
    def __init__(self, sale, percent):
        newsale = int(sale) / 100 * (100 + int(percent))
        print ("Новая цена равна -", int(newsale))    
class Main_function(Plus_to_price):
    def __init__(self):
        while True :
            sale = input("Введите нынешнюю цену -> ")
            percent = input("Введите процент, на который необходимо повысить цену -> ")
            if sale or percent == True:
                Plus_to_price.__init__(self, int(sale), int(percent))
            else:
                print ("Произошла ошибка! Вы не ввели данные!")
            print ("\n****************************\n")
main_function = Main_function()        
Master_Sergius
>>> a = 5
>>> isinstance(a, int)
True
>>> isinstance(a, str)
False
py.user.next
>>> a = 5
>>> type(a) == int
True
>>>
PanovSergey
http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python
>>> a = 5
>>> isinstance(a, int)
True
>>> isinstance(a, object)
True
>>> type(a) == int
True
>>> type(a) == object
False
>>> 
dimy44
 >>> type(a) == int
такая запись- имхо моветон.
PanovSergey
dimy44
такая запись- имхо моветон
подробнее? а то я вас не понимаю.
dimy44
Ну не по-питоняч'е это. Типа как if x == None вместо if x is None, isinstance да, норм.
FishHook
PanovSergey
подробнее? а то я вас не понимаю.
isinstance, в отличие от type
1. Принимает кортеж параметров
2. Поддерживает наследование

Плохо
print type(s) in [unicode, str]
Лучше
print isinstance(s, basestring)
PanovSergey
FishHook
isinstance, в отличие от type
Спасибо, Кэп!
Вы хоть сообщения прочитайте прежде чем ответить
MetalHead
Ребят, проверять научился, но в Python 3, все данные в input() типа str, так вот мне необходимо сделать так чтобы, пропускало только цифры, как можно проверить цифры ли в переменной, пример предоставляю:
class Plus_to_price:
    def __init__(self, sale, percent):
        newsale = int(sale) / 100 * (100 + int(percent))
        print ("Новая цена равна -", int(newsale))
        
class Change_type(Plus_to_price):
    def __init__(self, sale, percent):
        if isinstance(sale, int) or isinstance(percent, int) is True: #здесь ясно что будет False
            Plus_to_price.__init__(self, int(sale), int(percent))
        else:
            print ("Ошибка")
            
class Main_function(Change_type):
    def __init__(self):
        while True :
            sale = input("Введите нынешнюю цену -> ")
            percent = input("Введите процент, на который необходимо повысить цену -> ")
            Change_type.__init__(self, sale, percent) # а если преобразовывать в int, то в метод попадают кривые переменные
main_function = Main_function()  
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB