In [3]:
def foo(x):
    if x > 0:
        return x**2
    else:
        return None
    
if foo(10) is not None:
    print("Value is greater than 0")
else:
    print("Value is less than 0")
    
Value is greater than 0
In [4]:
n = int("1234")  # constructor
In [5]:
n
Out[5]:
1234
In [6]:
type(n)
Out[6]:
int

Simple Class Definition

In [12]:
class MyClass:  # New data type
    """A simple class definition"""
    i = 12345  # NOT a instance variable, but class variable
    
    def meth(self, x, s):
        self.big_str = s * x  # instance variable
In [8]:
lst = [1,2,3,4]
list(reversed(lst))
Out[8]:
[4, 3, 2, 1]
In [9]:
lst
Out[9]:
[1, 2, 3, 4]
In [10]:
lst.reverse()
In [11]:
lst
Out[11]:
[4, 3, 2, 1]
In [13]:
mc = MyClass()
In [14]:
mc
Out[14]:
<__main__.MyClass at 0x109330860>
In [15]:
type(mc)
Out[15]:
__main__.MyClass
In [16]:
dir(mc)
Out[16]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'i',
 'meth']
In [17]:
mc.meth()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-76786d619f5f> in <module>()
----> 1 mc.meth()

TypeError: meth() missing 2 required positional arguments: 'x' and 's'
In [19]:
mc.meth(3, "spam")
In [20]:
dir(mc)
Out[20]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'big_str',
 'i',
 'meth']
In [21]:
mc.big_str
Out[21]:
'spamspamspam'
In [23]:
class MyClass2:  # New data type
    """A simple class definition"""
    i = 12345  # NOT a instance variable, but class variable
    
    def __init__(self):
        pass
    
    def print_str(self):
        return self.big_str  # getter
    
    def meth(self, x, s):
        self.big_str = s * x  # instance variable
In [24]:
mc2 = MyClass2()
In [25]:
dir(mc2)
Out[25]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'i',
 'meth',
 'print_str']
In [26]:
mc2.print_str()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-8bfa943c3ab1> in <module>()
----> 1 mc2.print_str()

<ipython-input-23-da7ca8af98a7> in print_str(self)
      7 
      8     def print_str(self):
----> 9         return self.big_str  # getter
     10 
     11     def meth(self, x, s):

AttributeError: 'MyClass2' object has no attribute 'big_str'
In [27]:
mc2.meth(3, "ham")
In [28]:
mc2.print_str()
Out[28]:
'hamhamham'
In [29]:
class MyClass3:  # New data type
    """A simple class definition"""
    i = 12345  # NOT a instance variable, but class variable
    
    def __init__(self):
        """Initializer"""
        self.big_str = ""
    
    def print_str(self):
        return self.big_str  # getter
    
    def meth(self, x, s):
        self.big_str = s * x  # instance variable
In [30]:
mc3 = MyClass3()  # Constructor call
In [32]:
mc3.print_str()
Out[32]:
''
In [33]:
mc3.meth(3, "spam")
In [34]:
mc3.print_str()
Out[34]:
'spamspamspam'
In [41]:
class MyClass4:  # New data type
    """A simple class definition"""
    i = 12  # NOT a instance variable, but class variable
    
    def __init__(self):
        """Initializer"""
        self.big_str = ""
        print(self, id(self))
    
    def print_str(self):
        return self.big_str  # getter
    
    def meth(self, x, s):
        # self, x, s formal parameters, but they definitely local variables
        self.big_str = s * (x + self.i)  # instance variable
In [43]:
mc4 = MyClass4()
mc4.meth(3, "foobar")
print(mc4, id(mc4))
<__main__.MyClass4 object at 0x109336438> 4449330232
<__main__.MyClass4 object at 0x109336438> 4449330232
In [37]:
mc4.print_str()
Out[37]:
'foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar'
In [38]:
mc4.i
Out[38]:
12
In [39]:
mc4.big_str
Out[39]:
'foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar'
In [40]:
mc4.meth
Out[40]:
<bound method MyClass4.meth of <__main__.MyClass4 object at 0x10934ccc0>>

Complex Number

In [59]:
class Complex:
    def __init__(self, realpart=0, imagpart=0):
        # realpart, imagpart are both local variables
        self.realpart = realpart
        self.imagpart = imagpart
        
    def get_real(self):
        return self.realpart
    
    def get_imag(self):
        return self.imagpart
In [50]:
x = Complex(3.0, -4.5)
In [51]:
x
Out[51]:
<__main__.Complex at 0x1093c5240>
In [52]:
x.realpart
Out[52]:
3.0
In [53]:
x.imagpart
Out[53]:
-4.5
In [54]:
x.get_real()
Out[54]:
3.0
In [55]:
Complex
Out[55]:
__main__.Complex
In [56]:
type(Complex)
Out[56]:
type
In [57]:
dir(Complex)
Out[57]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'get_imag',
 'get_real']
In [58]:
dir(x)
Out[58]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'get_imag',
 'get_real',
 'imagpart',
 'realpart']
In [63]:
class Complex:
    def __init__(self, realpart=0, imagpart=0):
        # realpart, imagpart are both local variables
        self.realpart = realpart
        self.imagpart = imagpart
        
    def get_real(self):
        return self.realpart
    
    def get_imag(self):
        return self.imagpart
    
    @staticmethod
    def foo(x, y):
        return x, y
    
In [64]:
c = Complex()
In [65]:
c.foo(1,2)
Out[65]:
(1, 2)

Pet Class

In [88]:
class Pet:
    def __init__(self, species, name, age, gender):
        self.species = species
        self.name = name
        self.age = age
        self.gender = gender
        
    def human_age(self):
        if self.species == "canine":
            multi = 7  # 7 human years for every 1 dog year
            return self.age * multi
        elif self.species == "feline":
            raise NotImplementedError("Please create a feline calculation of human age!")
In [89]:
fido = Pet("canine", "Fido", 7, "m")
In [90]:
fido.human_age()
Out[90]:
49
In [91]:
felix = Pet("feline", "Felix", 14, "f")
In [92]:
felix.human_age()
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-92-76382997f531> in <module>()
----> 1 felix.human_age()

<ipython-input-88-21ff72b34291> in human_age(self)
     11             return self.age * multi
     12         elif self.species == "feline":
---> 13             raise NotImplementedError("Please create a feline calculation of human age!")

NotImplementedError: Please create a feline calculation of human age!
In [94]:
class Pet:
    def __init__(self, species, name, age, gender):
        self.species = species
        self.name = name
        self.age = age
        self.gender = gender
        self.tricks = []
        
    def human_age(self):
        if self.species == "canine":
            multi = 7  # 7 human years for every 1 dog year
            return self.age * multi
        elif self.species == "feline":
            raise NotImplementedError("Please create a feline calculation of human age!")
            
    def add_trick(self, trick):
        #self.tricks = self.tricks + [trick]
        self.tricks.append(trick)
In [95]:
fido = Pet("canine", "Fido", 7, "m")
In [96]:
fido.age
Out[96]:
7
In [97]:
fido.add_trick("Fetch")
In [98]:
fido.tricks
Out[98]:
['Fetch']