转自:http://www.programiz.com/article/python-self-why

If you have been programming in Python (in object oriented way of course) for some time, I'm sure you have come across methods that have self as their first parameter. It may seem odd, especially to programmers coming from other languages, that this is done explicitly every single time we define a method. As The Zen of Python goes, "Explicit is better than implicit".

So, why do we need to do this? Let's take a simple example to begin with. We have a Point class which defines a method distance to calculate the distance from origin.


class Point(object):
def __init__(self,x = 0,y = 0):
self.x = x
self.y = y def distance(self):
"""Find distance from origin"""
return (self.x**2 + self.y**2) ** 0.5

Let us now instantiate this class and find the distance.


>>> p1 = Point(6,8)
>>> p1.distance()
10.0

In the above example, __init__() defines three parameters but we just passed two (6 and 8). Similarly distance() requires one but zero arguments were passed. Why is Python not complaining about this argument number mismatch?

What Happens Internally?

Let me first clarify that Point.distance and p1.distance in the above example are a bit different.


>>> type(Point.distance)
<class 'function'>
>>> type(p1.distance)
<class 'method'>

We can see that the first one is a function and second, a method. A peculiar thing about methods (in Python) is that the object itself is passed on as the first argument to the corresponding function. In the case of the above example, the method call p1.distance() is actually equivalent toPoint.distance(p1). Generally, when we call a method with some arguments, the corresponding class function is called by placing the method's object before the first argument. So, anything likeobj.meth(args) becomes Class.meth(obj, args). The calling process is automatic while the receiving process is not (its explicit).

This is the reason the first parameter of a function in class must be the object itself. Writing this parameter as self is merely a convention. It is not a keyword and has no special meaning in Python. We could use other names (like this) but I strongly suggest you not to. Using names other than self is frowned upon by most developers and degrades the readability of the code ("Readability counts").

Self Can Be Avoided

By now you are clear that the object (instance) itself is passed along as the first argument, automatically. This implicit behavior can be avoided by making a method, static. Consider the following simple example.


class A(object): @staticmethod
def stat_meth():
print("Look no self was passed")

Here, @staticmethod is a function decorator which makes stat_meth() static. Let us instantiate this class and call the method.


>>> a = A()
>>> a.stat_meth()
Look no self was passed

From the above example, we are clear that the implicit behavior of passing the object as the first argument was avoided using static method. All in all, static methods behave like our plain old functions.


>>> type(A.stat_meth)
<class 'function'>
>>> type(a.stat_meth)
<class 'function'>

Self Is Here To Stay

The explicit self is not unique to Python. This idea was borrowed from Modula-3. Following is a use case where it becomes helpful.

There is no explicit variable declaration in Python. They spring into action on the first assignment. The use of self makes it easier to distinguish between instance attributes (and methods) from local variables. In, the first example self.x is an instance attribute whereas x is a local variable. They are not the same and lie in different namespaces.

Many have proposed to make self a keyword in Python, like this in C++ and Java. This would eliminate the redundant use of explicit self from the formal parameter list in methods. While this idea seems promising, it's not going to happen. At least not in the near future. The main reason is backward compatibility. Here is a blog from the creator of Python himself explaining why the explicit self has to stay.

__init__() is not a constructor

One important conclusion that can be drawn from the information so far is that, __init__() is not a constructor. Many na?ve Python programmers get confused with it since __init__() gets called when we create an object. A closer inspection will reveal that the first parameter in __init__() is the object itself (object already exists). The function __init__() is called immediately after the object is created and is used to initialize it.

Technically speaking, constructor is a method which creates the object itself. In Python, this method is __new__(). A common signature of this method is


__new__(cls, *args, **kwargs)

When __new__() is called, the class itself is passed as the first argument automatically. This is what the cls in above signature is for. Again, like self, cls is just a naming convention. Furthermore,*args and **kwargs are used to take arbitary number of arguments during method calls in Python.

Some important things to remember when implementing __new__() are:

  • __new__() is always called before __init__().
  • First argument is the class itself which is passed implicitly.
  • Always return a valid object from __new__(). Not mandatory, but thats the whole point.

Let's take a look at an example to be crystal clear.


class Point(object): def __new__(cls,*args,**kwargs):
print("From new")
print(cls)
print(args)
print(kwargs) # create our object and return it
obj = super().__new__(cls)
return obj def __init__(self,x = 0,y = 0):
print("From init")
self.x = x
self.y = y

Now, let's now instantiate it.


>>> p2 = Point(3,4)
From new
<class '__main__.Point'>
(3, 4)
{}
From init

This example illustrates that __new__() is called before __init__(). We can also see that the parameter cls in __new__() is the class itself (Point). Finally, the object is created by calling the__new__() method on object base class. In Python, object is the base class from which all other classes are derived. In the above example, we have done this using super().

Use __new__ or __init__?

You might have seen __init__() very often but the use of __new__() is rare. This is because most of the time you don't need to override it. Generally, __init__() is used to initialize a newly created object while __new__() is used to control the way an object is created. We can also use __new__()to initialize attributes of an object, but logically it should be inside __init__(). One practical use of__new__() however, could be to restrict the number of objects created from a class.

Suppose we wanted a class SqPoint for creating instances to represent the four vertices of a square. We can inherit from our previous class Point (first example in this article) and use__new__() to implement this restriction. Here is an example to restrict a class to have only four instances.


class SqPoint(Point):
MAX_Inst = 4
Inst_created = 0 def __new__(cls,*args,**kwargs):
if (cls.Inst_created >= cls.MAX_Inst):
raise ValueError("Cannot create more objects")
cls.Inst_created += 1
return super().__new__(cls)

A sample run.


>>> p1 = SqPoint(0,0)
>>> p2 = SqPoint(1,0)
>>> p3 = SqPoint(1,1)
>>> p4 = SqPoint(0,1)
>>>
>>> p5 = SqPoint(2,2)
Traceback (most recent call last):
...
ValueError: Cannot create more objects

The Story of self Parameter in Python, Demystified的更多相关文章

  1. 替换空格(C++和Python 实现)

    (说明:本博客中的题目.题目详细说明及参考代码均摘自 “何海涛<剑指Offer:名企面试官精讲典型编程题>2012年”) 题目 请实现一个函数,把字符串中的每个空格替换为 "%2 ...

  2. Python进阶-函数默认参数

    Python进阶-函数默认参数 写在前面 如非特别说明,下文均基于Python3 一.默认参数 python为了简化函数的调用,提供了默认参数机制: def pow(x, n = 2): r = 1 ...

  3. sqlmap使用手册

    转自:http://hi.baidu.com/xkill001/item/e6c8cd2f6e5b0a91b7326386 SQLMAP 注射工具用法 1 . 介绍1.1 要求 1.2 网应用情节 1 ...

  4. 小白眼中的AI之~Numpy基础

      周末码一文,明天见矩阵- 其实Numpy之类的单讲特别没意思,但不稍微说下后面说实际应用又不行,所以大家就练练手吧 代码裤子: https://github.com/lotapp/BaseCode ...

  5. sqlmap原理及使用方法

    1 . 介绍1.1 要求 1.2 网应用情节 1.3 SQL 射入技术 1.4 特点 1.5 下载和更新sqlmap 1.6 执照 2 . 用法2.1 帮助 2.2 目标URL 2.3 目标URL 和 ...

  6. Robot Framework接口测试(1)

    RF是做接口测试的一个非常方便的工具,我们只需要写好发送报文的脚本,就可以灵活的对接口进行测试. 做接口测试我们需要做如下工作: 1.拼接发送的报文 2.发送请求的方法 3.对结果进行判断 我们先按步 ...

  7. Allure-pytest功能特性介绍

    前言 Allure框架是一个灵活的轻量级多语言测试报告工具,它不仅以web的方式展示了简介的测试结果,而且允许参与开发过程的每个人从日常执行的测试中最大限度的提取有用信息从dev/qa的角度来看,Al ...

  8. Pytest系列(19)- 我们需要掌握的allure特性

    如果你还想从头学起Pytest,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1690628.html 前言 前面我们介绍了allure的 ...

  9. pytest(12)-Allure常用特性allure.attach、allure.step、fixture、environment、categories

    上一篇文章pytest Allure生成测试报告我们学习了Allure中的一些特性,接下来继续学习其他常用的特性. allure.attach allure.attach用于在测试报告中添加附件,补充 ...

随机推荐

  1. 搭建Titanium开发环境

    轻松制作 App 再也不是梦! Titanium Mobile 让你能够使用你所熟悉的 web 技术,制作出如同使用Objective-C 或 Java 写出的 Native App. 除了有多达三百 ...

  2. 转】Maven学习总结(七)——eclipse中使用Maven创建Web项目

    原博文出自于: http://www.cnblogs.com/xdp-gacl/p/4054814.html 感谢! 一.创建Web项目 1.1 选择建立Maven Project 选择File -& ...

  3. Altium Desiger自定义BOM导出格式

    用Excel做一个xx.xlt的2003的模版文件,如名为:AltiumDesiger PCB BOM Template.xlt 将AltiumDesiger PCB BOM Template.xlt ...

  4. shell脚本的入参

    shell脚本参数可以任意多,但只有前9个可以被访问,使用shift命令可以改变这个限制.参数从第一个开始,在第九个结束.$0 程序名字$n 第n个参数值,n=1..9 $* 所有命令行参数$@    ...

  5. eclipse/MyEclipse 日期格式、注释日期格式、时区问题[转]

    http://www.cnblogs.com/hoojo/archive/2011/03/21/1990070.html 在eclipse/MyEclipse中,如果你的注释或是运行System.ou ...

  6. 数据字符集mysql主从数据库,分库分表等笔记

    文章结束给大家来个程序员笑话:[M] 1.mysql的目录:在rpm或者yum安装时:/var/lib/mysql  在编译安装时默许目录:/usr/local/mysql 2.用rpm包安装的MyS ...

  7. 【转】C++笔试题汇总

    原文:http://www.cnblogs.com/ifaithu/articles/2657663.html C#C++C多线程面试1.static有什么用途?(请至少说明两种)1)在函数体,一个被 ...

  8. PI-利用SoapUI 测试web service的方法介绍

    在运用webservice调用数据的过程中,非常关键的一个步骤就是获取到webservice的地址,并测试webservice的连通情 况,webservice的连通测试主要是两个方面:1,查看web ...

  9. oracle批量导出AWR报告

    工作需求:项目中需要把生产库中所有的AWR报告dump出来,然后导入到方便测试的数据库中.在测试库中的AWR报告需要根据dbid和实例名逐个导出,如果遇到很多再加上RAC系统,会很麻烦.在网上找了一些 ...

  10. Android - FrameLayout覆盖顺序

    FrameLayout覆盖顺序 本文地址: http://blog.csdn.net/caroline_wendy FrameLayout: Child views are drawn in a st ...