8/17/2023 0 Comments Integer overflow python![]() ![]() well, for one thing, this works on floats too, and, on the other hand, it's easy to construct a class that is definitely not very numeric, yet defines the + operator in some way. Some people have pointed out that you should 'just do x + 1 and see whether that fails. Some people have pointed out that type-checking against int (and long) might loose cases where a big decimal number is encountered. It's really astounding to see such a heated discussion coming up when such a basic, valid and, i believe, mundane question is being asked. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it. This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. In other words, don't check whether x is an integer assume that it is and catch the exception results if it isn't: try: The classical Python mentality, though, is that it's easier to ask forgiveness than permission. This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one. ![]() For instance, if you subclass int, your new class should register as an int, which type will not do: class Spam(int): pass It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. Unless you are in Python 2.x in which case you want isinstance(, (int, long))ĭo not use type. If you need to do this, do isinstance(, int) ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |