每天推薦一個 GitHub 優質開源項目和一篇精選英文科技或編程文章原文,歡迎關注開源日報。交流QQ群:202790710;微博:https://weibo.com/openingsource;電報群 https://t.me/OpeningSourceOrg


今日推薦開源項目:《從零開始的操作系統(Ver2.0) os-tutorial》傳送門:GitHub鏈接

推薦理由:這應該是第二個關於操作系統的項目了,這個項目是一個創建操作系統的教程。對於一些人來說一開始就讀內核代碼可能實在有點太難了,所以作者決定自己寫簡單一些的創建操作系統教程。如果你們對使用樹莓派和 Linux 內核學習操作系統開發感興趣,也可以看看上一個從零開始。

傳送鏈接:https://openingsource.org/2840/


今日推薦英文原文:《Python Objects》作者:Stephen Chu

原文鏈接:https://medium.com/@stephen.chu530/python-objects-5c484d413d6f

推薦理由:介紹一個 Python 中的基本概念——什麼是對象

Python Objects

Introduction

For some of us learning Python, the behavior in Python can at times seem — quirky. To help ease the learning process, I』ll attempt to explain a fundamental concept that underlies everything in Python: Everything is an object! The sooner we can grasp this idea, the quicker we can start building things. For this short discussion, I』ll cover the concepts and the implementation of Python objects.


ID and Type

Before diving into the details, there are two key terms to keep in mind: IDs and Types.

IDs are unique integers for every object in Python. Each object』s ID lasts for the entire duration of the python interpreter or more practically speaking, for the entire duration the Python script is running. Coincidentally, the object ID is also the object』s location in memory.

To get an object』s ID, you can use the id() built-in function:

>>> a = 1
>>> id(a)
10964896

The number 10964896 is the object』s unique integer ID as well as it』s address space location.

To get an object』s type, you can use the type() built-in function:

>>> a = 1
>>> type(a)
<class 'int'>

There are several different types in Python:int, float, complex, str, list, frozenset, tuple,dict, function, set, class, object, and None. In the above example, the variable a is an inttype.


What is an Object?

So everything in Python is an object, and every object has a unique ID and has a type associated with it — but what exactly is an object?

An object is a type of variable that contains values and functions all grouped under one roof. This organization of values and functions are defined by a class. For example:

>>> class sample_class:
...     def __init__(self):
...         pass

The above class defines an object of the class sample_class. The details of the above example is not important, but know that every object in Python has a class definition that contains all the variables called attributes, and functions called methods that are associated with the object. An object is created based off their class definition and this action of creating an object is called instantiation.

>>> example = sample()
# An object 'example' is instantiated based on class 'sample_class'

Once an object is instantiated based on its class definition, what can we do wit

# ** Method 1: **
>>> list_b = [1, 2, 3]
>>> id(list_b)
140419576066824
>>> list_b += [4]
>>> list_b
[1, 2, 3, 4]

>>> id(list_b)
140419576066824
# the object ID does not change as expected

# ** Method 2: **
>>> list_b = list_b + [5]
>>> list_b
[1, 2, 3, 4, 5]

>>> id(list_b)
140419576066936
# the object ID changed! But this is not evidence that lists are
# immutable

 

h it? We can make changes to the object, but only if it is mutable.


Mutable objects

The definition of mutable means liable to change according to a quick Google search. In context of objects, mutable objects are objects that can change in place without having their IDs and type change. Let』s take a look at a list object:

>>> list_a= [1, 2, 3]
# list_a is a list type object with 3 elements

>>> id(list_a)
140423986856648
# this is the current ID of our list_a

>>> list_a.append(4)
# let's add a new element 4 to the list

>>> list_a
[1, 2, 3, 4]
# we see that 4 has been added

>>> id(list_a)
140423986856648
# the ID of list_a has not changed!

There are many other types that are mutable such as: bytearray, set, and dict. However a caveat: Depending on how you』re affecting change to these mutable types, a new object can be created, thus giving an impression the variable is immutable. For example:

The above example is a clear demonstration of changing a list in two different ways gives two different implications. The first way retains the ID, and thus shows the list is mutable. The second way does not retain the ID which confuses the matter. So is a list mutable or immutable? What we need to do is pay attention to how the expression is evaluated.

In Method 2, we changed the list using the list = list + element expression. This in fact creates a new object as shown, but it did not actually make changes to the object! It merely created a new object using the previous list plus the new element, and then assigned in back to the original pointer. The original object that contained [1, 2, 3, 4] is now sitting somewhere waiting to be garbage collected. The idea behind Method 2 is that even though on the surface it appears the list is not mutable, it actually is.

Another way to understand mutable objects is to use the value equality operator and the object ID comparison operator.

>>> a = [1, 2]
>>> b = [1, 2]
>>> a == b
True
>>> a is b
False
>>> id(a) == id(b)
False

From the above demonstration, both lists a and b have the same exact values, but their object IDs are different. This is the way of mutable objects to keep in mind.

Immutable objects

Immutable objects are objects that cannot change their contents. They are unchanging — aka immutable. Some examples of immutable objects are int, float, str, tuples, and frozenset.

Immutable objects are called immutable because once the object is allocated space in memory, it can no longer change. The ID of the object along with the contents of the object will not change. If we were to create an immutable object, and then we wanted to change it』s value, then what would happen is a new object is created in a new address space. Then the pointer would point to the new object. The first object will remain in memory until garbage collection gets rid of it. For example:

>>> a = "Hi"
>>> id(a)
140419576066824
# the string object contains the characters "Hi"
>>> a
Hi

>>> a += "t"
>>> id(a)
140419576066936
# as shown here, the ID has changed because strings are immutable
>>> a
Hit

>>> b = "Hi"
>>> id(b)
140419576066824
# the new pointer for object b resumes the previous a ID

Let』s try using the value equality operator and the object ID comparison operator.

>>> a = "Hi"
>>> b = "Hi
>>> a == b
True
>>> a is b
True
>>> id(a) == id(b)
True

Why Python treats mutable and immutable objects differently

The million dollar question regarding mutable and immutable objects in Python: Why are there two types? Is there some grand overall design decision why some objects are allowed to have their contents changed, while others are simply replaced all together?

According to Sean Conroy』s article, Mutable vs Immutable objects in Python, the primary reason for having mutable and immutable objects is that this allows for efficient handling of changing content.

For example, we can place multiple immutable strings into a mutable object like a list. Then using the list, we can then manipulate the different strings and concatenate them together without using additional space. If we were to perform concatenation on a group of strings without using a mutable object, then at each sub-stage during concatenation, additional memory space would be needed to hold the new string. This would be a colossal waste of resources.


How arguments are passed to functions and what does that imply for mutable and immutable objects

Every argument in Python is passed to functions in a process called Call-by-Object. What this means is that how the function handles the argument is entirely based on the type of object. In context of Python, the object being mutable or immutable is the determining factor.

For example, if we pass an integer into a function, then the function will treat the integer argument as 「pass-by-value」 because an integer is immutable. If a list was passed into a function, then the function will treat it like a 「pass-by-reference」 and can make changes to the contents of the list that will actually affect the caller』s list.

Understanding this subtle difference will help make working with objects in Python easier. Please consult the below sources for further reading and reference.



每天推薦一個 GitHub 優質開源項目和一篇精選英文科技或編程文章原文,歡迎關注開源日報。交流QQ群:202790710;微博:https://weibo.com/openingsource;電報群 https://t.me/OpeningSourceOrg