我想知道,这是在下面2种方法中声明字典的最佳实践,为什么?
>>>a=dict(one=2, two=3) # {"two":3, "one":2}
>>>a={"two":3, "one":2}
Run Code Online (Sandbox Code Playgroud) 可能重复:
访问python int literals方法
Python中的所有东西都是一个对象.甚至一个数字也是一个对象:
>>> a=1
>>> type(a)
<class 'int'>
>>>a.real
1
Run Code Online (Sandbox Code Playgroud)
我尝试了以下内容,因为我们应该能够访问对象的类成员:
>>> type(1)
<class 'int'>
>>> 1.real
File "<stdin>", line 1
1.real
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?
我是Python的三元运算符的新手
>>> 'true' if True else 'false' true
true
Run Code Online (Sandbox Code Playgroud)
我希望下面的代码输出为[],因为[]不等于None
>>> a=[]
>>> a==None
False
>>> a if a else None
None
Run Code Online (Sandbox Code Playgroud)
如果我错了,请求正确
谢谢赫马
我是python编程中的模拟和单元测试的新手,我如何在测试时模拟ex:age 10而不是27的函数的局部变量,请您修复以下代码。
# data_source.py
def get_name():
age = 27 #real value
return "Alice"
# person.py
from data_source import get_name
class Person(object):
def name(self):
return get_name()
from mock import patch
from person import Person
- unit test
@patch('person.age')
def test_name(mock_age):
mock_age = 10 # mock value
person = Person()
name = person.name()
assert age == 10
Run Code Online (Sandbox Code Playgroud) 我是python2.6编程的新手,我的目标是在os的temp目录中创建.txt或.xls"临时文件"并向其写入一些数据.然后在完成阅读后从"临时文件"中读取数据数据,从临时目录中删除"临时文件".
对于那个过程,我选择NamedTemporaryFile(),但无法实现.你能建议我怎样才能实现它.谢谢你.
>>> import os
>>> import tempfile
>>> with tempfile.NamedTemporaryFile() as temp:
print temp.name
temp.write('Some data')
f = open(os.path.join(tempfile.gettempdir(),temp.name))
lines = f.readlines()
f.close()
temp.flush()
c:\users\110\appdata\local\temp\tmpf8p3kc
Traceback (most recent call last):
File "<pyshell#3>", line 4, in <module>
f = open(os.path.join(tempfile.gettempdir(),temp.name))
IOError: [Errno 13] Permission denied: 'c:\\users\\110\\appdata\\local\\temp\\tmpf8p3kc'
Run Code Online (Sandbox Code Playgroud) 我正在开发自定义记录器程序,根据我需要获取进程,线程和对象名称的要求在被调用函数内部(在下面的示例中,它的obj需要在get_configured_logger函数内部获取)和obj所属的类名.如下面代码中的注释所示,请提供一些实现此目的的想法.
import logging, logging.handlers
from logging import StreamHandler, Formatter
class A:
def get_configured_logger(self,name):
logger = logging.getLogger(name)
if (len(logger.handlers) == 0):
FORMAT = "%(process)s %(thread)s:-(asctime)s - %(name)s - %(levelname)s - %(message)-%(module)"
#print 'process:',process
#print 'thread:',thread
#print 'levelname:',levelname
#print 'Module:',(name portion of filename).
#print 'obj:,'name of the object(Eg:obj),current function( Eg: get_configured_logger) called by'
#print 'class name:(obj is instance of class)'
formatter = logging.Formatter(fmt=FORMAT)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
if __name__=="__main__":
obj=A()
logger = obj.get_configured_logger("DEMO")
logger.debug("TEST")
Run Code Online (Sandbox Code Playgroud)
谢谢
HEMA
如何从函数内获取调用者对象,并检查有关该调用者的信息?
\n\nclass A(object):\n def class_A_fun(self):\n print \'caller from class\' # \xe2\x86\x92 B\n print \'caller from method\' # \xe2\x86\x92 class_B_fun\n print \'caller module\' # \xe2\x86\x92 foomodule\n print \'caller instance\' # \xe2\x86\x92 obj\n print \'caller object file name or path\' # \xe2\x86\x92 \'foomodule.py\'\n\nclass B(object):\n def class_B_fun(self): \n obj = A()\n obj.class_A_fun() \n\nif __name__ == "__main__":\n obj = B()\n obj.class_B_fun()\nRun Code Online (Sandbox Code Playgroud)\n 我是python编程的新手,试图去除包含正斜杠字符的字符串,我期望输出为'/ stack'但是给出如下结果.你能帮助我如何实现预期的输出.还有其他任何简单的方法来实现同样的目标.
>>> name='/stack/overflow'
>>> sub ='/overflow'
>>> name.strip(sub)
'stack'
Run Code Online (Sandbox Code Playgroud)
提前谢谢赫马
我是python编程的新手,python的美是Everything a Object,但为什么不将关键字作为对象呢?
>>> type(for)
File "<stdin>", line 1
type(for)
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud) 任何人都可以帮助我添加内存处理程序、缓冲处理程序,以使我的程序达到最佳状态(刷新缓冲内存)。
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)#we can set deug_level at logger level also
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.debug('This is a test log message.')
Run Code Online (Sandbox Code Playgroud) 我是python编程的新手,我想知道如何增强内置函数的功能(Monkeypatch)
例如
我知道sum()内置函数只允许在数字项上
>>> sum([4,5,6,7]) #22
Run Code Online (Sandbox Code Playgroud)
我想使sum函数允许项目列表为字符串,如下所示
例如
>>> sum(['s','t','a','c','k']) # 'stack'
Run Code Online (Sandbox Code Playgroud)
提前致谢