2015-06-24

Python 學習筆記

First edit: 2015/06/24
By: YigouDada

Python 學習筆記

這篇是我自己的 Python 學習筆記,同樣的.. 只會記下我自己特別留意到的東西。 XD

Python 是一種完全物件導向、直譯式的程式語言,其採用動態型別、強型別的設計。

Some Usefull Link

Built-in Functions and Class Constructers

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true.

len(s)

Return the length (the number of items) of an object.

class type(object)

Return the type of an object.

>>> type({})
<type 'dict'>
>>> type('') is str
True

Control Statement - for

並不像 C, Java 等語言,for 在 Python 中並不單純只是 while 語句的另一種替代寫法。 在 Python 中,for 語句被設計用來對可迭代(iterable)的物件當中的每個元素進行操作,像是 list, str 等。 相關範例如下:

words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))

Logic Operators

Python 保留 and, or, not 等 keyword 作為 logic operator 使用。

Bitwise Operators (on Integer)

  • &: bitwise AND
  • |: bitwise OR
  • ^: bitwise XOR
  • ~: bitwise NOT
  • >>: right shift
  • <<: left shift

Lambda Expression

Python 提供 lambda expression,可以用來實作 anonymous function。 相關範例如下:

lambda x: x%3 == 0
# above is the same as
def by_three(x):
    return x%3 == 0

# the following two function call do the same thing
filter(lambda x: x % 3 == 0, my_list)
filter(by_three, my_list)

Class Declaration

  • global variable
  • class variable
  • instance variable
  • global method
  • class method
  • instance method

Generic Syntax

class DerivedClass(BaseClassA, BaseClassB, ...):
    """Docstring"""
    def __init__(self, attriA, attriB, ...):    # Constructor
        self.attriA = attriA    # member variables
        self.attriB = attriB
    def __repr__(self):
        return "This is what will printed when print class instance"
    # other methods & attributes
    def someMethod(self, argA, argB, ...):      # start with self
        pass                                    # 
    memberVariable = inital_value

Overloading Class Method & Attribute

class Derived(Base)
    def someMethod(self):   # a method which is defined in Bass class
        pass
    # other methods & attributes

If we need to call a member from base class that is overloaded, we can access it by built-in super call.

class Derived(Base)
    def someMethod(self):   # a method which is defined in Bass class
        return super(Derived, self).someMethod()
    # other methods & attributes

File I/O

file can be open by open() built-in function, and be closed by call close() method of file.

someFile = open(fileName, mode)
someFile = open("data.txt", "rw")
someFile.write(outputData)
inputData = someFile.read()
inputData = someFile.readline()
somefile.close()
# somefile.closed == true

The list of open modes can be found here: Python Doc - open()

And we can use with ... as ... keywords to close file after using automatically.

with open("data.txt", "w" as someFile:
    someFile.write("Done!!\n")
# the file will close automatically