Rock It 《ML》JupyterLab 【丁】Code《四》

現在讀者已經清楚知道『可變性』 mutability 是由物件『類型』 type 而定,並不是借『身份』 id() 同異區分。大概不會驚訝

257 \  is \ not \ 257 吧!

 

事實上,a \ is \ b \ \equiv \ id(a) \ == \ id(b)

物件『可變性』的重要性在於,用多個『標識符』來存取,當物件異時異地為廣義運算更改時,這些『標識符』當下所指何物呢?

『不可變』物件︰『原物件』 5 保留於 b 。

 

『可變』物件︰『原物件』y = [1,2,3] 通常跟著 x 變也。

 

這使得派生『標識符』和『物件』間之關係十分微妙,不好與其他語言比類,所以『賦值陳述』方說『【再】綁定』乎??

7.2. Assignment statements

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

 

如是才能定奪需不需要『【深】拷貝』也!!

 

那麼講到物件『賦值』應該很簡單了吧!

讀讀下面文本,然後再次思考上面字句,自己回答耶?

6.10.1. Value comparisons

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects do not need to have the same type.

Chapter Objects, values and types states that objects have a value (in addition to type and identity). The value of an object is a rather abstract notion in Python: For example, there is no canonical access method for an object’s value. Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation.

Because all types are (direct or indirect) subtypes of object, they inherit the default comparison behavior from object. Types can customize their comparison behavior by implementing rich comparison methods like __lt__(), described in Basic customization.

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

A default order comparison (<, >, <=, and >=) is not provided; an attempt raises TypeError. A motivation for this default behavior is the lack of a similar invariant as for equality.

The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that.

The following list describes the comparison behavior of the most important built-in types.

  • Numbers of built-in numeric types (Numeric Types — int, float, complex) and of the standard library types fractions.Fraction and decimal.Decimal can be compared within and across their types, with the restriction that complex numbers do not support order comparison. Within the limits of the types involved, they compare mathematically (algorithmically) correct without loss of precision.

    The not-a-number values float('NaN') and Decimal('NaN') are special. They are identical to themselves (is x is true) but are not equal to themselves (x == x is false). Additionally, comparing any number to a not-a-number value will return False. For example, both 3 < float('NaN') and float('NaN') < 3 will return False.

  • Binary sequences (instances of bytes or bytearray) can be compared within and across their types. They compare lexicographically using the numeric values of their elements.

  • Strings (instances of str) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord()) of their characters. [3]

    Strings and binary sequences cannot be directly compared.

  • Sequences (instances of tuple, list, or range) can be compared only within each of their types, with the restriction that ranges do not support order comparison. Equality comparison across these types results in unequality, and ordering comparison across these types raises TypeError.

    Sequences compare lexicographically using comparison of corresponding elements, whereby reflexivity of the elements is enforced.

    In enforcing reflexivity of elements, the comparison of collections assumes that for a collection element x, x == x is always true. Based on that assumption, element identity is compared first, and element comparison is performed only for distinct elements. This approach yields the same result as a strict element comparison would, if the compared elements are reflexive. For non-reflexive elements, the result is different than for strict element comparison, and may be surprising: The non-reflexive not-a-number values for example result in the following comparison behavior when used in a list:

    >>> nan = float('NaN')
    >>> nan is nan
    True
    >>> nan == nan
    False                 <-- the defined non-reflexive behavior of NaN
    >>> [nan] == [nan]
    True                  <-- list enforces reflexivity and tests identity first

    Lexicographical comparison between built-in collections works as follows:

    • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
    • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).
  • Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs. Equality comparison of the keys and values enforces reflexivity.

    Order comparisons (<, >, <=, and >=) raise TypeError.

  • Sets (instances of set or frozenset) can be compared within and across their types.

    They define order comparison operators to mean subset and superset tests. Those relations do not define total orderings (for example, the two sets {1,2} and {2,3} are not equal, nor subsets of one another, nor supersets of one another). Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, min(), max(), and sorted() produce undefined results given a list of sets as inputs).

    Comparison of sets enforces reflexivity of its elements.

  • Most other built-in types have no comparison methods implemented, so they inherit the default comparison behavior.

User-defined classes that customize their comparison behavior should follow some consistency rules, if possible:

  • Equality comparison should be reflexive. In other words, identical objects should compare equal:

    x is y implies x == y

  • Comparison should be symmetric. In other words, the following expressions should have the same result:

    x == y and y == x

    x != y and y != x

    x < y and y > x

    x <= y and y >= x

  • Comparison should be transitive. The following (non-exhaustive) examples illustrate that:

    x > y and y > z implies x > z

    x < y and y <= z implies x < z

  • Inverse comparison should result in the boolean negation. In other words, the following expressions should have the same result:

    x == y and not x != y

    x < y and not x >= y (for total ordering)

    x > y and not x <= y (for total ordering)

    The last two expressions apply to totally ordered collections (e.g. to sequences, but not to sets or mappings). See also the total_ordering() decorator.

  • The hash() result should be consistent with equality. Objects that are equal should either have the same hash value, or be marked as unhashable.

Python does not enforce these consistency rules. In fact, the not-a-number values are an example for not following these rules.

 

 

 

 

 

 

 

Rock It 《ML》JupyterLab 【丁】Code《三》

為什麼『元祖』

4.6.5. Tuples

Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a set or dict instance).

class tuple([iterable])
Tuples may be constructed in a number of ways:

  • Using a pair of parentheses to denote the empty tuple: ()
  • Using a trailing comma for a singleton tuple: a, or (a,)
  • Separating items with commas: a, b, c or (a, b, c)
  • Using the tuple() built-in: tuple() or tuple(iterable)

The constructor builds a tuple whose items are the same and in the same order as iterable’s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For example, tuple('abc') returns ('a', 'b', 'c') and tuple( [1, 2, 3] ) returns(1, 2, 3). If no argument is given, the constructor creates a new empty tuple, ().

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a, b, c)is a function call with three arguments, while f((a, b, c)) is a function call with a 3-tuple as the sole argument.

Tuples implement all of the common sequence operations.

For heterogeneous collections of data where access by name is clearer than access by index,collections.namedtuple() may be a more appropriate choice than a simple tuple object.

 

稱之為『不可變』物件呢?並非因為其『身份』 id() 不改也。而是這個『容器』不可變也!

 

舊瓶固可裝新酒,那瓶子不變也。

 

所以醞釀發酵,直把『函式』之『pass by value』── immutable ──以及『call by reference』── mutable ── 容成一爐矣!!

 

或許這只點出了『函式』語法定義規矩︰

8.6. Function definitions

A function definition defines a user-defined function object (see section The standard type hierarchy):

funcdef        ::=  [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
decorators     ::=  decorator+
decorator      ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
dotted_name    ::=  identifier ("." identifier)*
parameter_list ::=  (defparameter ",")*
                    | "*" [parameter] ("," defparameter)* ["," "**" parameter]
                    | "**" parameter
                    | defparameter [","] )
parameter      ::=  identifier [":" expression]
defparameter   ::=  parameter ["=" expression]
funcname       ::=  identifier

A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.

The function definition does not execute the function body; this gets executed only when the function is called. [3]

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code

@f1(arg)
@f2
def func(): pass

is roughly equivalent to

def func(): pass
func = f1(arg)(f2(func))

except that the original function is not temporarily bound to the name func.

When one or more parameters have the form parameter = expression, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters up until the “*” must also have a default value — this is a syntactic restriction that is not expressed by the grammar.

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

Function call semantics are described in more detail in section Calls. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary. Parameters after “*” or “*identifier” are keyword-only parameters and may only be passed used keyword arguments.

Parameters may have annotations of the form “: expression” following the parameter name. Any parameter may have an annotation even those of the form *identifier or **identifier. Functions may have “return” annotation of the form “-> expression” after the parameter list. These annotations can be any valid Python expression and are evaluated when the function definition is executed. Annotations may be evaluated in a different order than they appear in the source code. The presence of annotations does not change the semantics of a function. The annotation values are available as values of a dictionary keyed by the parameters’ names in the __annotations__attribute of the function object.

It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda expressions, described in section Lambdas. Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a “def” statement can be passed around or assigned to another name just like a function defined by a lambda expression. The “def” form is actually more powerful since it allows the execution of multiple statements and annotations.

Programmer’s note: Functions are first-class objects. A “def” statement executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section Naming and binding for details.

See also

PEP 3107 – Function Annotations
The original specification for function annotations.

恐還難跨越『可呼叫』者︰

callable(object)

Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.

New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.

※ 参考︰

3.3.5. Emulating callable objects

object.__call__(self[, args…])

Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

 

『術語』準繩,尚未知『第一類公民』何物哩。

也許『郭沫若』說的好︰

』是『』的,書是『』的。『』『』讀『』『』,可以把『』讀『』。『』『』讀『』『』,可以把『』讀『』。

如何『』 Python ?就從『』本『派生』的『』開始。因『』故及於它『』它『』,以至於『』而已!!

□︰ 難道都不用練習的嗎?

○︰此語未免太癡!《論語》

學而』篇開宗明義講︰『』而時『』之的吧!!

比方說《潜入派生》 Dive into Python 第二章第四節

《 2.4. Everything Is an Object 》講︰

2.4.2. What’s an Object?

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function’s source code. The sys module is an object which has (among other things) an attribute called path. And so forth.

Still, this begs the question. What is an object? Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4).

This is so important that I’m going to repeat it in case you missed it the first few times: everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.

那麼我們將如何理解『在派生中,一切皆是物件。』這句話呢?要是不深入『派生』的『語法』以及『語意』,只依靠著『語用』根本是不足以『回答』的吧!而且不同的『程式語言』,『口號』不同,『哲學』也不一樣!!Python 號稱『多典範』,『程序』為主的寫作、『物件』中心之編程,『泛函式』概念的淺嚐,……等等,也許可以這麼說︰

『派生』支持的『作法』,讓它『語法』上『方便容易』。

『派生』不支持的『行事』,也可『己選自擇』的『表現』。

因此想要掌握 Python 語言,『深思』、『細慮』以及『多實驗』或許是個好的起步。就像嘗試看看,在『派生』中,什麼是『函式』 function 的呢?

pi@raspberrypi ~ $ python3
Python 3.2.3 (default, Mar  1 2013, 11:53:50) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

# 列出『整數』物件有的『屬性』與『方法』
>>> dir(3)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']


# 『泛函式』小試
>>> def 求值(函數,參數):
...     return 函數(參數)
... 

# 『函數』定義
>>> def f(x):
...     return x*x +2*x -1
... 

# 『函數』求值
>>> 求值(f,5)
34

# f 是『函數』物件的『標識符』
>>> f
<function f at 0x76a5cf60>

# 『函數』呼叫,是由『標識符』 f 與『參數元組』 (5) 所構成
>>> f (5)
34

# 『函數』的重要『屬性』是『可呼叫』 callable
>>> callable(f)
True

# 列出『函數』物件有的『屬性』與『方法』
>>> dir(f)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

# λ 『匿名函數』
>>> 求值(lambda x:x*x + 2*x -1,5)
34

>>> lambda x:x*x + 2*x -1
<function <lambda> at 0x76a5ced0>

>>> dir(lambda x:x*x + 2*x -1)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

 

─── 豈是一句『可呼叫』 callable 了得!! ───

─── 摘自《W!O 的派生‧十日談之《七》

 

 

 

 

 

 

 

Rock It 《ML》JupyterLab 【丁】Code《二》

既然 Python 語言參考文件說︰

所有物件都有一個身份、類型和賦值。

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is’ operator compares the identity of two objects; the id() function returns an integer representing its identity.

理應仔細推敲含意,嘗試用於各種物件,確立清楚明白陳述也。

舉例而言︰

None

This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false.

類似 C 的『void』,代表『虛空』或『沒有』。

是否符合那三個條件呢?

進而釐清『意指』,最好與『空字串』、『整數零』、『空串列』 、『空字典』等等作『對比』︰

真實了解深入該物件也!

如斯者有著追根究底的精神,故不會隨便放過一字一句,往往認識深刻、理解全面呦◎

比方講,絕不會忽略下面這個

『不可改』 unchangeable

『不可變』 immutable

『可變』 mutable

區分之重要字句︰

An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable. [1]

The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

【『不可變』通常 id() 不變】

【『不可變』可以 id() 有變】

【『可變』一定 id() 不同】

 

心中自然知道物件『拷貝』 copy 因何而生矣☆

8.10. copyShallow and deep copy operations

Source code: Lib/copy.py


Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

Interface summary:

copy.copy(x)
Return a shallow copy of x.
copy.deepcopy(x)
Return a deep copy of x.
exception copy.error
Raised for module specific errors.

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Two problems often exist with deep copy operations that don’t exist with shallow copy operations:

  • Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
  • Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.

The deepcopy() function avoids these problems by:

  • keeping a “memo” dictionary of objects already copied during the current copying pass; and
  • letting user-defined classes override the copying operation or the set of components copied.

This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

Shallow copies of dictionaries can be made using dict.copy(), and of lists by assigning a slice of the entire list, for example, copied_list = original_list[:].

Classes can use the same interfaces to control copying that they use to control pickling. See the description of module pickle for information on these methods. In fact, the copy module uses the registered pickle functions from the copyreg module.

In order for a class to define its own copy implementation, it can define special methods __copy__() and__deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the__deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument.

See also

Module pickle
Discussion of the special methods used to support object state retrieval and restoration.

或樂知有一本 Python 2.7《 The Right Way 》指南吧︰

Fundamental Data Types

None

None
Object that denotes the lack of value.

Numbers

bool
True and False Boolean values. Evaluate to 1 and 0 respectively.
int
Integer numbers.
long
Long integer numbers.
float
Floating point numbers.
complex
Complex numbers.

Sequences

str
Strings of characters. Immutable.
`unicode`_
Unicode strings of characters. Immutable.
list
Indexed list of objects. Mutable.
tuple
Indexed list of objects. Immutable.

Mappings

dict
Hash table for storing unordered key-value pairs. Mutable.

Sets

set
Unordered list of unique objects. Mutable.

Files

file
File objects.

 

 

 

 

 

 

Rock It 《ML》JupyterLab 【丁】Code《一》

雖說第一個高階程式語言是德國 Konrad Zuse 先生的 Plankalkül,大約構想於第二次世界大戰末期,然而第一個廣為使用的卻是福傳 Fortran ── Formula Translation 的縮寫。1957 年IBM 當時的工程師約翰·華納·巴克斯 John Warner Backus 因深切體會到編寫程式困難,需要更好的程式語言所創。他也就是知名的『 BNF 』巴科斯 -諾爾範式 Backus–Naur Form 的創始者之一,這個範式 是一種表示無上下文脈絡關係 Context Free 文法語言,可以用來描述 CF 這一類的形式語言,這包括了絕大部分的電腦程式語言。其後又有了 1969 年在 Bell Labs circa 由 Ken ThompsonDennis Ritchie 所發展的 B 語言,然後於 1971 年之際演變成 New B,最終於 1972 年變成了今天的 C 語言 ── After B ──,形成了美麗的『ABC』語言傳奇

事實上 Von Neumann 的計算機架構,對於電腦程式語言的發展,有著極為深遠的影響,產生了現在叫做 Von Neumann 程式語言,與Von Neumann 的計算機架構,同形 isomorphism 同構

program variables ↔ computer storage cells
程式變數 對映  計算機的儲存單元

control statements ↔ computer test-and-jump instructions
控制陳述 對映 計算機的『測試.跳至』指令

assignment statements ↔ fetching, storing instructions
賦值陳述 對映 計算機的取得、儲存指令

expressions ↔ memory reference and arithmetic instructions.
表達式 對映 記憶體參照和算術指令

John Warner Backus 曾經斷言,由於電腦圈長期過度強調 Von Neumann 的程式語言與計算機架構,已經產生了『惡性循環』,使得非此類的語言由於不符合經濟而日漸式微,比方 APL 語言 ── 註︰有興趣的,可以參照這裡在 Raspbian 上安裝 ──。

─── 《CPU 機器語言的『解譯器』

人能說話解語,未必能通熟文法!此所以成為學習電腦語言之障礙乎?就像才三十三個『關鍵字』 keyword 的 python3

看似容易掌握其『文法』,實則『語意』及『語用』並不容易也。

如果不能深入派生三『資料模型』

3. Data model

3.1. Objects, values and types

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer,” code is also represented by objects.)

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is’ operator compares the identity of two objects; the id()function returns an integer representing its identity.

CPython implementation detail: For CPython, id(x) is the memory address where x is stored.

An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable. [1]

The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly).

Note that the use of the implementation’s tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a ‘tryexcept’ statement may keep objects alive.

Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The ‘tryfinally’ statement and the ‘with’ statement provide convenient ways to do this.

Some objects contain references to other objects; these are called containers. Examples of containers are tuples, lists and dictionaries. The references are part of a container’s value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.

Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and dare guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)

………

即使認識整數一之『字面符號』 literals ,這個『物件』 object 裡有什麼內涵也不容易哩!!

 

就像說︰如何知『賦值陳述』

7.2. Assignment statements

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" target_list ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target

(See section Primaries for the syntax definitions for attributeref, subscription, and slicing.)

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy).

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

  • If the target list is empty: The object must also be an empty iterable.
  • If the target list is a single target in parentheses: The object is assigned to that target.
  • If the target list is a comma-separated list of targets, or a single target in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.
    • If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty).
    • Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Assignment of an object to a single target is recursively defined as follows.

  • If the target is an identifier (name):

    • If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.
    • Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal, respectively.

    The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.

  • If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, TypeError is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError).

    Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the RHS expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The LHS target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the RHS expression refers to a class attribute, the LHS creates a new instance attribute as the target of the assignment:

    class Cls:
        x = 3             # class variable
    inst = Cls()
    inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3

    This description does not necessarily apply to descriptor attributes, such as properties created withproperty().

  • If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

    If the primary is a mutable sequence object (such as a list), the subscript must yield an integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).

    If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

    For user-defined objects, the __setitem__() method is called with appropriate arguments.

  • If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it.

CPython implementation detail: In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2]:

x = [0, 1]
i = 0
i, x[i] = 1, 2         # i is updated, then x[i] is updated
print(x)

See also

PEP 3132 – Extended Iterable Unpacking
The specification for the *target feature.

當起於已有之『物件』,而非無所指的『標識符』 identifiers 耶?

6.2. Atoms

Atoms are the most basic elements of expressions. The simplest atoms are identifiers or literals. Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms. The syntax for atoms is:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom

6.2.1. Identifiers (Names)

An identifier occurring as an atom is a name. See section Identifiers and keywords for lexical definition and section Naming and binding for documentation of naming and binding.

When the name is bound to an object, evaluation of the atom yields that object. When a name is not bound, an attempt to evaluate it raises a NameError exception.

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.

6.2.2. Literals

Python supports string and bytes literals and various numeric literals:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber

Evaluation of a literal yields an object of the given type (string, bytes, integer, floating point number, complex number) with the given value. The value may be approximated in the case of floating point and imaginary (complex) literals. See section Literals for details.

All literals correspond to immutable data types, and hence the object’s identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value.

………

 

先此旁敲側引,不過是『倒吃甘蔗』呦◎

 

 

 

 

 

 

Rock It 《ML》JupyterLab 【丁】灯引旋風

220px-Albert_Einstein_photo_1921

物理哲學之重要性

220px-Wooden_hourglass

時間意指改變

CalabiYau5

卡拉比-丘流形

320px-MassProperties.svg

質量的面貌

Einstein’s work on the importance of the philosophy of physics

“I fully agree with you about the significance and educational value of methodology as well as history and philosophy of science. So many people today—and even professional scientists—seem to me like somebody who has seen thousands of trees but has never seen a forest. A knowledge of the historic and philosophical background gives that kind of independence from prejudices of his generation from which most scientists are suffering. This independence created by philosophical insight is—in my opinion—the mark of distinction between a mere artisan or specialist and a real seeker after truth.”Einstein. letter to Robert A. Thornton, 7 December 1944. EA 61-574.

“How does it happen that a properly endowed natural scientist comes to concern himself with epistemology? Is there no more valuable work in his specialty? I hear many of my colleagues saying, and I sense it from many more, that they feel this way. I cannot share this sentiment. … Concepts that have proven useful in ordering things easily achieve such an authority over us that we forget their earthly origins and accept them as unalterable givens. Thus they come to be stamped as ‘necessities of thought,’ ‘a priori givens,’ etc.”

The path of scientific advance is often made impassable for a long time through such errors. For that reason, it is by no means an idle game if we become practiced in analyzing the long-commonplace concepts and exhibiting [revealing, exposing? -Ed.] those circumstances upon which their justification and usefulness depend, how they have grown up, individually, out of the givens of experience. By this means, their all-too-great authority will be broken.” Einstein, 1916, “Memorial notice for Ernst Mach,” Physikalische Zeitschrift 17: 101-02.

……

愛因斯坦認為物理哲學之所以重要,有著教育上的價值,在於說,物理哲學是關於如何看待,人們所知之大自然的整體科學知識。不僅僅只是物理知識、物理方法以及物理理論與假設之反思的總括。這個哲學嘗試在我們已知的和未知的知識之間建立橋樑,闡述人類思維能力所可能達到的領域極限,並且說明人的這種探索之價值。

 

── 或許有一天,人類終會知道人是什麼??

就像刻在古希臘戴爾菲神廟

上之,蘇格拉底的名言︰認識自己!!  ──

─── 《物理哲學·上

灯下讀好書,亮點熱蒸騰。
腦海注理念,心頭旋風生。

猶恐『天下一指、萬物一馬』

人們習以為常的語言、文字都是符號系統。當我們講到玫瑰花,是指「可以看、聞、摸的那種植物的花」,如果缺乏感官經驗,也許根本不能知道玫瑰花是什麼?或者正因為經驗的自然平常,以致於我們忘了玫瑰花只是個符號。有人說玫瑰花即使換個名字‥ Rose ,依然芬芳香甜,指的就是這個道理。如同月亮高掛天空,只能一指說月;天下廣大,當然也只能一指而知,所以說萬物雖然眾多,可以用像談馬一樣的東西去理解。在歷史上大數學家邱奇的 λ 演算,把數學的形式系統推上了高峰,同時加深了人們對『數是什麼?』的認識。

一朵花、一隻鳥、一座山、一片林…都是一,知道『』、又知道『加上一』,就可以知道數的無窮無盡。然而對於無窮無盡的數又該怎樣命名呢?古代中國發明了十倍為單位的記數法︰十十為百、十百為千、十千為萬…。初期用一、二、三、四、五、六、七、八 、九、十來書寫,而後因為需要發展了大寫數字‥壹、貳、參、肆 、伍、陸、柒、捌、玖、拾。至於說為什麼用十呢?也許因為人有十個手指頭,常用來數數指物。那為什麼沒有零呢?中國古代並沒有零的符號,在概念上『九章算術』用「無入」來表達,算盤上用「空位」去說明。現在所使用的阿拉伯記數法︰0、1、2、3、4、5、6、7、8、9,是在漫漫歷史長河中逐步變遷而來。由上述可知三百、參佰、300 雖然說的是同一個數,它的符號卻是不同的。同樣可以知道阿拉伯記數法用位置代表數量級,所以 0 的加入是必要的。

─── 摘自《天下一指、萬物一馬︰二進制

 

說 JupyterLab 『符碼格子』 Code Cell ,大而不當也;

又不宜在『部落格』 Blog 著書立論。

所以照舊,對 Python3 語言某些核心概念,略為分解發揮;

至於好書,樂於分享耳◎

/WhirlwindTourOfPython

The Jupyter Notebooks behind my OReilly report, “A Whirlwind Tour of Python”

A Whirlwind Tour of Python

Jake VanderPlas, Summer 2016

This repository contains the Jupyter Notebooks behind my O’Reilly report, A Whirlwind Tour of Python (free 100-page pdf).

A Whirlwind Tour of Python is a fast-paced introduction to essential components of the Python language for researchers and developers who are already familiar with programming in another language.

The material is particularly aimed at those who wish to use Python for data science and/or scientific programming, and in this capacity serves as an introduction to The Python Data Science Handbook (also with notebooks on github). These materials are adapted from courses and workshops I’ve given on these topics at University of Washington and at various conferences, meetings, and workshops around the world.

This material was written and tested using Python 3.5, and should work for any Python 3.X version. I have done my best to note places where the syntax of Python 2.X will differ.

License and Citation

This material is released under the “No Rights Reserved” CC0 license, and thus you are free to re-use, modify, build-on, and enhance this material for any purpose. Read more about CC0 here.

If you do use this material, I would appreciate attribution. An attribution usually includes the title, author, publisher, and ISBN. For example:

A Whirlwind Tour of Python by Jake VanderPlas (O’Reilly). Copyright 2016 O’Reilly Media, Inc., 978-1-491-96465-1.