每天推荐一个 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 int
type.
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.
Sources
每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg
没有Python基础,看了两遍终于懂了,,,其实感觉自己蛮蠢的 😕 因为看完第二遍发现作者实际上讲得很清楚,配合代码讲解好评