1. 程式人生 > >筆記-pyton內建資料型別

筆記-pyton內建資料型別

筆記-pyton內建資料型別

1.      簡介

The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.

 

2.      操作

2.1.    真值測試

所有物件都可以做真值測試,可以在if 或while的條件語句中,也可以用布林操作。

物件做真值測試優先呼叫__bool__返回真則測試為真,否則為假;

沒有定義bool的話呼叫__len__ 返回為真則測試為真。

大部分內建物件真值測試方法如下:

constants defined to be false: None and False.

zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

empty sequences and collections: '', (), [], {}, set(), range(0)

 

2.2.    boolena operations- and,or,not

要注意的是or 和and是short-circuit operator,會返回第一個符合條件的條件式值;

not的運算級別比非布林運算低,not a == b 等效於not ( a == b ),而a == not b語法錯誤。

 

2.3.    比較運算

除非定義__eq__()方法,否則類的非相同例項的比較結果是不等。

總之,一般不要比較不同的類。

 

2.4.    int,float,complex

 

Operation

Result

Notes

Full documentation

x + y

sum of x and y

 

 

x - y

difference of x and y

 

 

x * y

product of x and y

 

 

x / y

quotient of x and y

 

 

x // y

floored quotient of x and y

(1)

 

x % y

remainder of x / y

(2)

 

-x

x negated

 

 

+x

x unchanged

 

 

abs(x)

absolute value or magnitude of x

 

abs()

int(x)

x converted to integer

(3)(6)

int()

float(x)

x converted to floating point

(4)(6)

float()

complex(re, im)

a complex number with real part re, imaginary part im. im defaults to zero.

(6)

complex()

c.conjugate()

conjugate of the complex number c

 

 

divmod(x, y)

the pair (x // y, x % y)

(2)

divmod()

pow(x, y)

x to the power y

(5)

pow()

x ** y

x to the power y

(5)

 

 

2.5.    integer型別的位元操作

只有整數可以進行位元運算。

 

Operation

Result

Notes

x | y

bitwise or of x and y

(4)

x ^ y

bitwise exclusive or of x and y

x & y

bitwise and of x and y

異或

x << n

x shifted left by n bits

移位

x >> n

x shifted right by n bits

移位

~x

the bits of x inverted

取反

 

2.6.    整數型別的附加方法

 

 

 

2.7.    序列

通用操作

Operation

Result

Notes

x in s

True if an item of s is equal to x, else False

(1)

x not in s

False if an item of s is equal to x, else True

(1)

s + t

the concatenation of s and t

(6)(7)

s * n or n * s

equivalent to adding s to itself n times

(2)(7)

s[i]

ith item of s, origin 0

(3)

s[i:j]

slice of s from i to j

(3)(4)

s[i:j:k]

slice of s from i to j with step k

(3)(5)

len(s)

length of s

 

min(s)

smallest item of s

 

max(s)

largest item of s

 

s.index(x[, i[, j]])

index of the first occurrence of x in s (at or after index i and before index j)

(8)

s.count(x)

total number of occurrences of x in s

 

 

mutable和immutable

 

Operation

Result

Notes

s[i] = x

item i of s is replaced by x

 

s[i:j] = t

slice of s from i to j is replaced by the contents of the iterable t

 

del s[i:j]

same as s[i:j] = []

 

s[i:j:k] = t

the elements of s[i:j:k] are replaced by those of t

(1)

del s[i:j:k]

removes the elements of s[i:j:k] from the list

 

s.append(x)

appends x to the end of the sequence (same as s[len(s):len(s)] = [x])

 

s.clear()

removes all items from s (same as dels[:])

(5)

s.copy()

creates a shallow copy of s (same as s[:])

(5)

s.extend(t) or s += t

extends s with the contents of t (for the most part the same as s[len(s):len(s)]= t)

 

s *= n

updates s with its contents repeated ntimes

(6)

s.insert(i, x)

inserts x into s at the index given by i(same as s[i:i] = [x])

 

s.pop([i])

retrieves the item at i and also removes it from s

(2)

s.remove(x)

remove the first item from s where s[i]is equal to x

(3)

s.reverse()

reverses the items of s in place

(4)

 

 

 

3.      binary sequence types-bytes,bytearray,memoryview

常使用的是bytes和bytearray,memoryview主要是為了實現在不復制的情況下訪問二進位制物件(使用buffer protcol)。

bytes是不可變的,bytearray是可變的。

bytearray支援常規序列操作。

有兩個方法fromhex(),hex()知道即可

 

The methods on bytes and bytearray objects don’t accept strings as their arguments, just as the methods on strings don’t accept bytes as their arguments. For example, you have to write:

a = "abc"

b = a.replace("a", "f")

and:

a = b"abc"

b = a.replace(b"a", b"f")

其它操作都與list比較相似,不囉嗦。

 

3.1.    memoryviews

memoryview物件允許python程式碼訪問物件的內部資料,當然,這個物件必需支援buffer procotol。

 

class memoryvies(obj)

建立一個memoryview物件,它引用obj。obj必需支援buffer protocol,就目前而言,內建的型別可以使用memoryview的有bytes和bytearray。

 

A memoryview supports slicing and indexing to expose its data. One-dimensional slicing will result in a subview:

>>> 

>>> v = memoryview(b'abcefg')

>>> v[1]

98

>>> v[-1]

103

>>> v[1:4]

<memory at 0x7f3ddc9f4350>

>>> bytes(v[1:4])

b'bce'

 

簡單點就是,str和bytearray的切片操作會產生新的切片str和bytearry並拷貝資料,使用memoryview之後不會。

 

不使用memoryview

 

>> a = 'aaaaaa'

>> b = a[:2]    # 會產生新的字串

 

>> a = bytearray('aaaaaa')

>> b = a[:2]    # 會產生新的bytearray

>> b[:2] = 'bb' # 對b的改動不影響a

>> a

bytearray(b'aaaaaa')

>> b

bytearray(b'bb')

使用memoryview

 

>> a = 'aaaaaa'

>> ma = memoryview(a)

>> ma.readonly  # 只讀的memoryview

True

>> mb = ma[:2]  # 不會產生新的字串

 

>> a = bytearray('aaaaaa')

>> ma = memoryview(a)

>> ma.readonly  # 可寫的memoryview

False

>> mb = ma[:2]      # 不會會產生新的bytearray

>> mb[:2] = 'bb'    # 對mb的改動就是對ma的改動

>> mb.tobytes()

'bb'

>> ma.tobytes()

'bbaaaa'

 

4.      set types – set, frozenset

 

A set object is an unordered collection of distinct hashable objects.

有兩種內建集合型別,set and frozenset。

frozenset是不可變的set;

通用操作,與數學上一樣的,交併差

len(s)

 

x in s

 

x not in s

 

isdisjoint(other)

是否有交集

issubset(other)

set <=other

 

 

discard(elem) 如果存在,則刪除

 

5.      dict

常規的沒什麼好講的,賦值,取值,賦值(預設值),fromkeys(),get()pop(),popitem(),update(),values(),keys(),items()

d = dict.fromkeys(range(15),8)

 

5.1.    dict view obj

The objects returned by dict.keys()dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

基本上當做一個可迭代物件使用就可以了。

 

6.      context manager types

python 的with 語句支援一個概念:上下文管理

有兩個方法:

contextmanager.__enter__()

 

contextmanager.__exit__(exc_typeexc_valexc_tb)

Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the with statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are None.

在with語句中的程式碼產生的異常首先會傳遞給exit方法,如果它返回True,則異常不會繼續傳播。這也是with的目的,無論異常與否,都會執行__exit__()。

 

一個簡單案例:

class TraceBlock(object):

    def message(self, arg):
        print('running ' + arg)

    def __enter__(self):
        print('starting with block')
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        if exc_type is None:
            print('exited normally\n')
        else:
            print('raise an exception! ' + str(exc_type))
            return False  # Propagate


if __name__ == '__main__':
    with TraceBlock() as action:
        action.message('test1')
        print('reached')

    with TraceBlock() as action:
        action.message('test2')
        raise TypeError
        print('not reached')

 

7.      其它內建型別

7.1.    modules

模組字典:__dict__ module’s symbol table

它可以直接修改,但不建議,m.__dict__={}是非法的。

 

7.2.    methods and functions

Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list).

 

Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as append() on lists) and class instance methods. Built-in methods are described with the types that support them.

可以理解為mehtods是可以使用屬性記號呼叫的functions。

另外有個概念bound method需要注意,簡單來說,呼叫繫結方法時會自動傳入self引數。

 

print(type(None))

>>> <class 'NoneType'>

 

7.3.    type

可以參考元類。

 

7.4.    NULL

 

This object is returned by functions that don’t explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name). type(None)() produces the same singleton.

It is written as None.

 

 

7.5.    Special Attributes

The implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by thedir() built-in function.

object.__dict__

A dictionary or other mapping object used to store an object’s (writable) attributes.

instance.__class__

The class to which a class instance belongs.

class.__bases__

The tuple of base classes of a class object.

definition.__name__

The name of the class, function, method, descriptor, or generator instance.

definition.__qualname__

The qualified name of the class, function, method, descriptor, or generator instance.

New in version 3.3.

class.__mro__

This attribute is a tuple of classes that are considered when looking for base classes during method resolution.

class.mro()

This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__.

class.__subclasses__()

Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. Example:

>>> int.__subclasses__()
[<class 'bool'>]