IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> Python __new__method testifying and my other perspectives -> 正文阅读

[Python知识库]Python __new__method testifying and my other perspectives

After an afternoon I've finally got a basic understanding of python's __new__method. Although still do I feel sorrow for the scanty knowledge because the basic implementation is still C, which I even haven't begun.

路漫漫其修远兮,吾将上下而求索。

The way ahead is long; I see no ending,yet high and low I'll search with my will unbending.

The general idea which inspired me is a pseudo-code from the book named Fluent Python,?collected at page 615:

#From book <Fluent Python>, author Luciano Ramalho

#It is a summarised pseudocode of the process of building an object in Python.


#pseudo-code for Python object construction
def object_maker(the_class, some_arg):
	new_object=the_class.__new__(some_arg)
	if isinstance(new_object, the_class):
		the_class.__init__(new_object, some_arg)
		return new_object

#the following statemenets are roughly equivalent:
x=Foo('bar')
#and
x=object_maker(Foo, 'bar')

The pseudocode above is really manifest. The reason we call it pseudocode is because the source code is C, but it is achieved by python. Nonetheless, it doesn't matter for understanding what's going on:

As we see, once an instance is created, __new__ method, the customed class's __new__method,?is the first one being processed. And the most interesting one is that the customed __init__ method is still processed before the new_object returning. Which means:

In every object creation, both the?__new__?and the?__init__?methods are run. The non-obvious behavior is the?__new__?calls?__init__. This is why?__init__?methods do not include a?return?statement. The newly created and initialized object is returned by the?__new__?method. Think of the?__init__?method as merely sprucing up the newly create object with attribute values, etc.? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

---copied from Chris Freemanhttps://teamtreehouse.com/community/why-do-i-have-to-use-self-strnewargs-kwargs-i-tried-not-using-it-and-it-worked

So, the real constructor method is __new__. The reason we often refer to __init__ as the constructor method is because we adopted jargon from other languages. __new__ umst return an instance, and that instance will in turn be passed as the first argument self,?then goes on constructing other instance methods by ourselves.

The following code is what I used?to testify:

import json

class TraditionalCar:
	def __new__(cls, *args, **kwargs):
		print('Construct a new object...')
		Name=kwargs.pop('Name')
		Wheel_num=kwargs.pop('Wheel_num')
		Medium=kwargs['Medium']
		Fuel=kwargs['Fuel']
		if Name:
			print('I have been processed.')
			return kwargs
		else:
			return super().__new__(cls) #equal to: return object.__new__(cls)
		
	def __init__(self, *args, **kwargs):
		print('Initialise a new object')
		self._name=kwargs.pop('name')
		self._price=kwargs.pop('price')
		self._first_appreared_time=kwargs.pop('first_appeared_time')
		
	def __str__(self):
		print('The properties of the car are:')
		return json.dumps(self.__dict__)

if __name__=='__main__':
	print('object_construction pseudocode testifying:')
	
	MyFavor=TraditionalCar(
	Name='Car',
	Wheel_num='4',
	Medium='Road',
	Fuel='Petroleum',
	name='Audi R8',
	price='$143,000',
	first_appeared_time='2006')
	
	print(type(MyFavor))
	print(MyFavor)


output:
object_construction pseudocode testifying:
Construct a new object...
I have been processed.
<class 'dict'>
{'Medium': 'Road', 'Fuel': 'Petroleum', 'name': 'Audi R8', 'price': '$143,000', 'first_appeared_time': '2006'}

What a strange thing but not all in threotical. The __new__ method in the code above doesn't construct an object because it returns a list kwargs, which turns the TraditionalCar() into a dict class. Which means __init__ doesn't initialise the class and all kwargs becomes the key and values of an instance of dict data structure.

But?when the Name in __new__ is not True:

import json

class TraditionalCar:
	def __new__(cls, *args, **kwargs):
		print('Construct a new object...')
		Name=kwargs.pop('Name')
		Wheel_num=kwargs.pop('Wheel_num')
		Medium=kwargs['Medium']
		Fuel=kwargs['Fuel']
		if not Name:
			print('I have been processed.')
			return kwargs
		else:
			return super().__new__(cls) #equal to: return object.__new__(cls)
		
	def __init__(self, *args, **kwargs):
		print('Initialise a new object')
		self._name=kwargs.pop('name')
		self._price=kwargs.pop('price')
		self._first_appreared_time=kwargs.pop('first_appeared_time')
		
	def __str__(self):
		print('The properties of the car are:')
		return json.dumps(self.__dict__)

if __name__=='__main__':
	print('object_construction pseudocode testifying:')
	
	MyFavor=TraditionalCar(
	Name='Car',
	Wheel_num='4',
	Medium='Road',
	Fuel='Petroleum',
	name='Audi R8',
	price='$143,000',
	first_appeared_time='2006')
	
	print(type(MyFavor))
    print(type(TraditionalCar))
	print(TraditionalCar.__bases__)
	print(MyFavor)



output:
object_construction pseudocode testifying:
Construct a new object...
Initialise a new object
<class '__main__.TraditionalCar'>
<class 'type'>
(<class 'object'>,)
The properties of the car are:
{"_name": "Audi R8", "_price": "$143,000", "_first_appreared_time": "2006"}


__init__ method has been successfully processed and the object has been?successfully created.?But remember, it is construced by the __new__ method of the base object: object!!?

If the customed class is inherited from another. It may become a bit different:

class ReversedStr(str):
    def __new__(cls, *args, **kwargs):
        self = str.__new__(cls, *args, **kwargs)  #cls included here too
        self = self[::-1]
        return self

# Console:
# test = ReversedStr("Hello")
# >>>test
# output: "olleH"

It is because:?The advantage of using the?super?or?str.__new__?is be able to use the automatic type converters built into the?str.__new__?method and gain access to the slicing methods available to the?str?class.

---copied from Chris FreemanWhy do I have to use self = str.__new__(*args, **kwargs)? I tried not using it and it worked. (Example) | Treehouse Community

Furthermore, if we go deeper for the class inheritance, which is really complicated but still significant for pointing out, is : if the code is like the underneath:

class A:
    def __new__(cls, ''' *args, **kwargs'''):
        return super().__new__(cls, ''' *args, **kwargs''')

You are not allowed to add more arguments after cls (cls stands for class A) or an error will be raised:

TypeError: object.__new__() takes exactly one argument (the type to instantiate)

This error can be found in CPython's source code, which is opened on github:

static PyObject *
object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    if (excess_args(args, kwds)) {
        if (type->tp_new != object_new) {
            PyErr_SetString(PyExc_TypeError,
                            "object.__new__() takes exactly one argument (the type to instantiate)");
            return NULL;
        }
        if (type->tp_init == object_init) {
            PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments",
                         type->tp_name);
            return NULL;
        }
    }

Because every class is automatically inherited from object, the basic object. Yes, the basic object is object, which is a basic knowledge. However, when I go deeper... We all know creating a class is actually using type(), the metaclass. And if you gather them within several sentences:

>>> class A:
...     pass
... 
>>> a=A()
>>> A.__bases__
(<class 'object'>,)
>>> A.__class__
<class 'type'>
>>> a.__bases__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute '__bases__'
>>> a.__class__
<class '__main__.A'>
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> 
>>> object.__bases__
()
>>> object.__class__
<class 'type'>
>>> type.__bases__
(<class 'object'>,)
>>> type.__class__
<class 'type'>
>>> 

I won't explain that much.

Maybe one day I will be?expertised in C.... And I will turn back finding out.

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-03-04 15:30:49  更:2022-03-04 15:31:48 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/31 4:10:20-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码