中企动力 > 头条 > python中name

网站性能检测评分

注:本网站页面html检测工具扫描网站中存在的基本问题,仅供参考。

python中name

Python学习笔记——3.基本的输入和输出 企业视频课程

img

聂怀绿

关注

注:这类文章是写给我自己看的。今天分享出来,如果对读者有帮助,我很高兴!

Python语言非常的“不规范”啊,和我之前学习的C差距比较大。C里面输入输出相对于Python来说,比较的繁琐……但是很规范!可以说是详细的描述的内存中发生的事情。

基本输出print( )

在NotePad++上开始编译自己的第一个简单的Python程序。伟大的"Hello,world!"

经典的“Hello,world”

可以看出来,和C差距比较大,在C语言中,输出时printf()函数,这里是print( ),意思很明确,就是英文“打印”的意思。

下面是几种输出格式的对比:

对比图

数字不用加字符串符号

基本输入input()

初次了解input()

数字测试输入

由此可见,python太随性了……从另一方面来看,这也是为什么很多人说python开发速度快,毕竟打字速度就那么快,那么简单。(C语言这方面就太严谨了,很能锻炼人的计算机思维)

总结:

print()输出

1.输出数字,不用加单引号或者双引号,但是输入字符串、字符,必须要加单引号或者双引号。

2.每个Python语句的结尾不用加分号“;”,而C语言中必须加。否则程序错误。

3.下面是数字加单引号和不加单引号的区别:

数字加不加单、双引号的区别

4.由上面可以推出,print()中,不加单、双引号,代表的是变量,或者数值,值!一旦加了,那么就被当成字符处理。(重点对比print(name)这个例子,其中,name是得到值的变量)

input()输入

使用input()输入的时候,必须指明一个存储变量,否则,没办法调用存储值input()括号内,无论你填入什么字符或者数字,加不加单双引号都不影响存储,因为全都当做字符串处理(有点不确定)input()还有一种另类输入:

便捷输入输出

便捷输入输出注意地方

记住:每天都要总结!学习!反思!早日成为一名黑客!

声明:这是本人学习笔记,给自己看的,现在分享给读者,如果对读者有帮助,我很开心。读者喜欢,可以关注我!点赞!收藏!

Python基础内容:怎样快速理解if __name__ ==‘main’语句 行业视频课程

img

永恒

关注

__name__ 是当前模块名,当模块被直接运行时模块名为 __main__ 。这句话的意思就是,当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。

相信好多初学者在学习python的过程中,经常会遇到if __name__ == 'main'语句,可能你知道它的作用,也可能很模糊,今天就给大家分享下我的理解。

我们先新建一个text的py文件,并写入以下内容并运行

然后呢,在同一个文件夹中在新建一个py文件text1,写入一行代码:import text 然后运行看看结果

与之前test.py代码运行结果比较,只有输出学习Python,也就是if __name__=="__main__": 之前的语句被执行,之后的没有被执行。

为什么会这样呢?别急,我们稍微处理下代码就可以看明白了:在 if __name__=="__main__"之前加入一行代码:print(__name__),即打印出__name__,然后我们在重新分别执行2个代码看看

这就很清楚了,在text中__name__变量的值为__main__,而在text1中,__name__的值为text,明显不满足if语句,因此,后面的代码无法执行!

仔细想想,它的原理也就是:

每个python模块(文件)都包含内置的变量__name__,当该模块被执行的时候,__name__就等于文件名。而import到其他模块(文件)中,则__name__等于当前的模块名,而__main__等于当前文件名,所以直接执行模块的时候if __name__=="__main__"为真,可以执行;import到其他模块(文件)中,if __name__=="__main__"为假,那当然就不执行对应的代码了。

简单说就是:__name__是当前的模块名字,在当前文件时可以被执行,而模块被导入时,代码不被运行!

喜欢就关注下呗( ̄ε  ̄)

Python IDLE no module name numpy 营销视频课程

img

池塘边

关注

Python IDLE 是Python的简单开发工具,当然你可以使用PyCharm,

在IDLE中使用numpy包时提示 no module name numpy,需要安装numpy包。

打开IDLE,打开 File--->Path Browser如下图所示:

path browser

然后转到python3.6目录使用pip3安装:

安装numpy

关闭IDLE后重新打开,可以使用numpy包。

导入numpy

有问题留言。

如何在 Python 中正确的代理对象 互联网视频课程

img

小兔子

关注

本文基于 Python 3.6

题外话

先来看一个问题: 已知对于一个对象来说,运算符 > 会去调用对象的 __gt__ 方法:

已知对于对象来说,__getattribute__ 在寻找实例属性时被无条件调用:

那么根据亚里士多德的三段论来说,我们可以使用一个 override __getattribute__ 方法的对象去代理对象 t 的所有方法,实现一个简单的对象代理:

好像的确可行,但是

重新整理一下思路,> 对去调用对象的 __gt__ 方法,而 __getattribute__ 会去截获属性寻找的过程,返回 t 对象的 __gt__ 方法,所以这种问题应该是前提出现了偏差

根据错误信息可以知道 __getattribute__ 没起作用,翻阅文档可知

Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

正题

那么如何正确地实现一个对象的代理呢?其实 __getattribute__ 也可以,不过要在 Proxy 类中也显示的定义 __gt__ 等 special method。但是 __getattribute__ 在编程时要极为留意,避免 maximum recursion depth exceeded,还是 __getattr__ 更加 friendly

Celery 源代码中有一个现成的实现(她自己声称是 stolen from werkzeug.local.Proxy)

def _default_cls_attr(name, type_, cls_value):

# Proxy uses properties to forward the standard

# class attributes __module__, __name__ and __doc__ to the real

# object, but these needs to be a string when accessed from

# the Proxy class directly. This is a hack to make that work.

# -- See Issue #1087.

def __new__(cls, getter):

instance = type_.__new__(cls, cls_value)

instance.__getter = getter

return instance

def __get__(self, obj, cls=None):

return self.__getter(obj) if obj is not None else self

return type(bytes_if_py2(name), (type_,), {

'__new__': __new__, '__get__': __get__,

})

class Proxy(object):

"""Proxy to another object."""

# Code stolen from werkzeug.local.Proxy.

__slots__ = ('__local', '__args', '__kwargs', '__dict__')

def __init__(self, local,

args=None, kwargs=None, name=None, __doc__=None):

object.__setattr__(self, '_Proxy__local', local)

object.__setattr__(self, '_Proxy__args', args or ())

object.__setattr__(self, '_Proxy__kwargs', kwargs or {})

if name is not None:

object.__setattr__(self, '__custom_name__', name)

if __doc__ is not None:

object.__setattr__(self, '__doc__', __doc__)

@_default_cls_attr('name', str, __name__)

def __name__(self):

try:

return self.__custom_name__

except AttributeError:

return self._get_current_object().__name__

@_default_cls_attr('qualname', str, __name__)

def __qualname__(self):

return self._get_current_object().__qualname__

@_default_cls_attr('module', str, __module__)

def __module__(self):

return self._get_current_object().__module__

@_default_cls_attr('doc', str, __doc__)

def __doc__(self):

return self._get_current_object().__doc__

def _get_class(self):

return self._get_current_object().__class__

@property

def __class__(self):

return self._get_class()

def _get_current_object(self):

"""Get current object.

This is useful if you want the real

object behind the proxy at a time for performance reasons or because

you want to pass the object into a different context.

"""

loc = object.__getattribute__(self, '_Proxy__local')

if not hasattr(loc, '__release_local__'):

return loc(*self.__args, **self.__kwargs)

try: # pragma: no cover

# not sure what this is about

return getattr(loc, self.__name__)

except AttributeError: # pragma: no cover

raise RuntimeError('no object bound to {0.__name__}'.format(self))

def __dict__(self):

return self._get_current_object().__dict__

except RuntimeError: # pragma: no cover

raise AttributeError('__dict__')

def __repr__(self):

obj = self._get_current_object()

return '<{0} unbound>'.format(self.__class__.__name__)

return repr(obj)

def __bool__(self):

return bool(self._get_current_object())

return False

__nonzero__ = __bool__ # Py2

def __dir__(self):

return dir(self._get_current_object())

return []

def __getattr__(self, name):

if name == '__members__':

return getattr(self._get_current_object(), name)

def __setitem__(self, key, value):

self._get_current_object()[key] = value

def __delitem__(self, key):

del self._get_current_object()[key]

def __setslice__(self, i, j, seq):

self._get_current_object()[i:j] = seq

def __delslice__(self, i, j):

del self._get_current_object()[i:j]

def __setattr__(self, name, value):

setattr(self._get_current_object(), name, value)

def __delattr__(self, name):

delattr(self._get_current_object(), name)

def __str__(self):

return str(self._get_current_object())

def __lt__(self, other):

return self._get_current_object() < other

def __le__(self, other):

return self._get_current_object() <= other

# omit some special method

另外说一点,使用 _default_cls_attr 而不用 property 装饰器 可以参考 issue 1087

从 class 访问 property 会返回 property 的实例

原因貌似好像是这个 (依据等价实现)

所以 Celery 自己搞了一个 descriptor

喜欢的话关注收藏评论转发比心么么哒!Python学习交流群330637182内有大量的项目开发和新手教学视频五千人大群等着你来加入

Python中如何防止sql注入 营销视频课程

img

Rousse

关注

sql注入中最常见的就是字符串拼接,研发人员对字符串拼接应该引起重视,不应忽略。

错误用法1:

sql = "select id, name from test where id=%d and name='%s'" %(id, name)

cursor.execute(sql)

错误用法2:

sql = "select id, name from test where id="+ str(id) +" and name='"+ name +"'"

cursor.execute(sql)

正确用法1:

args = (id, name)

sql = "select id, name from test where id=%s and name=%s"

cursor.execute(sql, args)

execute()函数本身有接受sql语句参数位的,可以通过python自身的函数处理sql注入问题。

正确用法2:

name = MySQLdb.escape_string(name)

sql = "select id, name from test where id=%d and name='%s'" %(id, name)

cursor.execute(sql)

python模块MySQLdb自带针对mysql的字符转义函数escape_string,可以对字符串转义。

深入学习Python3 if __name__=='__main__' 代表了什么意思 互联网视频课程

img

Yelena

关注

自学了很久的Python,水平一直不上不下,很恼火。所以现在打算整理一下自己大脑中关于Python的内存。

if __name__=='__main__':print(file_size(100,False))print(file_size(100))

这段代码是我在pycharm中敲出来的,刚开始并不明白它的意思是什么。后来问了度娘之后,明白了其中的奥秘。

看到if语句,有点编程基础的人都应该知道这是一个判断语句,当if后面的值未true时,后面的代码块才会被执行。反之则不会。

__name__代表当前文件的名字,__main__代表的是当前被执行的文件的名字。

下面看一个简单的例子,来做一下说明。

直接新建一个test.py文件,输入如下代码:

print ('I'm the first.')

if __name__=='__main__':

print ('I'm the second.')

直接执行test.py文件的结果如下:

可以看到两个print语句均被执行。

下面在同一个文件夹中新建import_test.py文件

只在文件中输入:import test

然后执行import_test.py文件,执行结果如下:

可以看到第二个print语句并咩有被执行。所以我们可以判断此时 __name__=='__main__':结果为false。那是因为在import_test.py文件中的__name__==import_test(没有包含后缀名),而__main__==import_test.py(包含后缀名),所以在import之后,if语句之后的print方法没有被执行。

如果看文字觉得太绕的话,我们可以在test.py文件中将__name__的值打印出来,大家看一下:

运行结果显示 __name__==__main__,所以在test.py文件中if语句后的print语句页被执行了。

同样,再执行import_test.py文件,可以看到输出结果如下:

此时__name__==test,if __name__=='__main__':结果为false所以在执行import_test.py文件时,if语句之后的print函数并咩有被执行。

img

在线咨询

建站在线咨询

img

微信咨询

扫一扫添加
动力姐姐微信

img
img

TOP