almost 4 years ago

python 是最近新學的 language, 記錄目前用到的語法中,有需要注意的地方

python type

built-in type function

built-in type
>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True

custom types

custom types
>>> class Test1 (object):
        pass
>>> class Test2 (Test1):
        pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True

built-in isinstance function

isinstance
>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True

Data Type in python

built-in data types

string class

  • str class is used to hold Unicode strings
  • bytes class is used to hold binary data.

append vs. extend on python list

  • append adds an element to a list
  • extend concatenates the first list with another list (or another iterable not necessarily a list.)
using append
x = [1, 2, 3]
x.append([4, 5])
print (x)

gives you: [1, 2, 3, [4, 5]]

using extend
x = [1, 2, 3]
x.extend([4, 5])
print (x)

gives you: [1, 2, 3, 4, 5]

← mongo note on 2014-11-21 mongo note on 2014-12-03 →