Skip to content

Instantly share code, notes, and snippets.

@tuannvm
Created February 24, 2017 09:29
Show Gist options
  • Save tuannvm/d529f5e4496b9f2acecaf11f8a8267d8 to your computer and use it in GitHub Desktop.
Save tuannvm/d529f5e4496b9f2acecaf11f8a8267d8 to your computer and use it in GitHub Desktop.

Introduction

Loop

  • For

Full form

dataList = []
tempList = []
for elem in dataList:
    tempList.append(func(elem))

print dataList

Short form

tempList = [func(elem) for elem in dataList]

File I/O

  • Open()

open (<filename>, <access mode>)

w a w+

# open file data.out in write mode
out = open("data.out", "w") 

# write "content" to out
print >>out, "content"

# close the file when done
out.close()
  • finally

when you have a situation when code must always run no matter what erros occur.

if you try to change an immutable value, Python raises a TypeError exception

data = open('file.txt')

# using locals() to check whether data object (file.txt represent) exists or not
if 'data' in locals():
        data.close()
  • with

with open('file.txt', 'w') as data:
    print >>data, "content here"

is equivalent to

data = open('file.txt', 'w')
print >>data, "content here"
data.close()

without additional close()

And also, two with statements````` can be combined with comma ","

OOP


Inheritance

class Decimal(object):
    """ define base class """
    def __init__(self, number, place):
        self.number = number
        self.place = place

    def __repr__(self):
        """ method to automatically return the value when call class itself"""
        return "%.{}f".format(self.place) % self.number

class Currency(Decimal):
    def __init__(self, number, place, symbol):
        """ inherit from Decimal class, initilize the attribute which base class support """
        super(Currency, self).__init__(number, place)
        self.symbol = symbol

    def __repr__(self):
        """ use the __repr__ method from base class to get the value """
        return "{}{}".format(self.symbol, super(Currency, self).__repr__())

print Decimal(2,5)
print Currency(3,5,'$')     
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment