Advanced Python (Fall 2017)/lecture7

From EIK wiki

Lecture 7

Data types

Data type things to know

clases in python describe datatype, and when called, create a new object of that type. type returns the datatype isinstance check if object is an instance of the class

In [3]: class A:
   ...:     pass
   ...:

In [4]: type(A)
Out[4]: type

In [5]: type(int)
Out[5]: type

In [6]: int(10)
Out[6]: 10

In [7]: float(10)
 Out[7]: 10.0

In [8]: isinstance(10, int)
Out[8]: True

In [9]: isinstance(10, float)
Out[9]: False

In [10]: class MyInt(int):
    pass
   ....:

In [11]: a = MyInt(10)

In [12]: a
Out[12]: 10

In [13]: type(a)
Out[13]: __main__.MyInt

In [14]: isinstance(a, int)
Out[14]: True

Magic Methods

there are prefixed and suffixed with '__', sometimes called 'dunder' for 'double underscore'.

They define specific python functionality.

class A:
    def __init__(self):
        pass

    def __str__(self):
        return 'I am an instance of A'


a = A()
print(a.__str__())
print(str(a))

Task 1

Make an integer which is: equal to both 5, 6 and the actual number (itself) greater than 3 less than 2

Solution

from unittest import TestCase


class MyInt(int):
    """Define some magic methods!"""
    def __lt__(self, x):
        if x == 2:
            return True
        else:
            return super().__lt__(x)

    def __gt__(self, x):
        if x == 3:
            return True
        else:
            return super().__gt__(x)

    def __eq__(self, x):
        if x == 5 or x == 6:
            return True
        else:
            return super().__eq__(x)


class MyIntTestCase(TestCase):
    def test_gt(self):
        a = MyInt(1)
        self.assertTrue(a > 3)

    def test_lt(self):
        a = MyInt(100)
        self.assertTrue(a < 2)

    def test_eq(self):
        a = MyInt(1)
        self.assertTrue(a == 5)
        self.assertTrue(a == 6)

```