Clojure中是否内置了与Python any和all函数类似的函数?
例如,在Python中,它就是all([True, 1, 'non-empty string']) == True.
可能重复:
Python中的"最小惊讶":可变默认参数
我今天下午写了一些代码,偶然发现了代码中的一个错误.我注意到我的一个新创建的对象的默认值是从另一个对象转移的!例如:
class One(object):
def __init__(self, my_list=[]):
self.my_list = my_list
one1 = One()
print(one1.my_list)
[] # empty list, what you'd expect.
one1.my_list.append('hi')
print(one1.my_list)
['hi'] # list with the new value in it, what you'd expect.
one2 = One()
print(one2.my_list)
['hi'] # Hey! It saved the variable from the other One!
Run Code Online (Sandbox Code Playgroud)
所以我知道这可以通过这样解决:
class One(object):
def __init__(self, my_list=None):
self.my_list = my_list if my_list is not None else []
Run Code Online (Sandbox Code Playgroud)
我想知道的是......为什么?为什么Python类是结构化的,以便在类的实例中保存默认值?
提前致谢!
在python中,repr和backquote 之间有区别`(左边是1)吗?
用于演示:
class A(object):
def __repr__(self):
return 'repr A'
def __str__(self):
return 'str A'
>>> a = A()
>>> repr(a)
#'repr A'
>>> `a`
#'repr A'
>>> str(a)
#'str A'
Run Code Online (Sandbox Code Playgroud)
反引号只是打电话repr吗?这只是为了方便吗?有明显的速度差异吗?
谢谢!
我想编写一个接受路径作为字符串或文件对象的函数.到目前为止,我有:
def awesome_parse(path_or_file):
if isinstance(path_or_file, basestring):
f = open(path_or_file, 'rb')
else:
f = path_or_file
with f as f:
return do_stuff(f)
Run Code Online (Sandbox Code Playgroud)
这里do_stuff需要一个打开的文件对象.
有一个更好的方法吗?请问with f as f:有什么反响?
谢谢!
我刚刚找到了Sublime Text 2,它真棒.我唯一真正想念的是能够查看我正在处理的函数的doc字符串.有没有可以做到这一点的插件?
例如:
def f(x):
'''a doc string for f'''
print x
f # << at this point, either automatically or with a keystroke,
# I would like to be able to somehow view "a doc string for f"
Run Code Online (Sandbox Code Playgroud)
编辑:我已经尝试过使用SublimeCodeIntel和SublimeRope,都没有这样的支持.
Edit2:它也应该适用于打开项目中的其他模块.
这可能是一个简单的问题,但我似乎无法掌握它.
我在models.py中有两个简单的模型:服务和主机.Host.services与Service有m2m关系.换句话说,主机有多个服务,一个服务可以驻留在多个主机上; 一个基本的m2m.
models.py
class Service(models.Model):
servicename = models.CharField(max_length=50)
def __unicode__(self):
return self.servicename
class Admin:
pass
class Host(models.Model):
#...
hostname = models.CharField(max_length=200)
services = models.ManyToManyField(Service)
#...
def get_services(self):
return self.services.all()
def __unicode__(self):
return self.hostname
class Admin:
pass
Run Code Online (Sandbox Code Playgroud)
admin.py
from cmdb.hosts.models import Host
from django.contrib import admin
class HostAdmin(admin.ModelAdmin):
list_display = ('get_services',)
admin.site.register(Host, HostAdmin)
Run Code Online (Sandbox Code Playgroud)
现在,当我打开列出所有主机列的页面时,"service"列显示输出,如:
获得服务
[<Service: the_service-1>, <Service: the_service-2>]
代替:
服务
the_service-1
the_service-2等
我究竟做错了什么?感谢您阅读我的问题.
我正在尝试打印Option<Box<MyStruct>>,但在尝试实现时遇到编译错误Display for Option<Box<MyStruct>>.
use std::fmt;
fn main() {
let maybe_my_struct: Option<Box<MyStruct>> = Some(Box::new(MyStruct{foo:42}));
println!("{}", maybe_my_struct);
}
struct MyStruct {
foo: i32,
}
impl fmt::Display for Option<Box<MyStruct>> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match self {
Some(MyStruct) => write!(formatter, "{}", self.foo),
None => write!(formatter, "No struct"),
}
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
error: the impl does not reference any types defined in this crate;
only traits defined in the current crate can be implemented for arbitrary …Run Code Online (Sandbox Code Playgroud) 我想使用 将编码标签包含在 XML 文档中BeautifulSoup.BeautifulStoneSoup,但我不确定如何!
<?xml version="1.0" encoding="UTF-8"?>
<mytag>stuff</mytag>
Run Code Online (Sandbox Code Playgroud)
当我阅读已经有它的文档时,它会输出编码标签,但我正在制作新汤。
谢谢!
编辑:我将举例说明我目前正在做的事情。
from BeautifulSoup import BeautifulStoneSoup, Tag
soup = BeautifulStoneSoup()
mytag = Tag(soup, 'mytag')
soup.append(mytag)
str(soup)
# '<mytag></mytag>'
soup.prettify() # No encoding given
# '<mytag>\n</mytag>'
soup.prettify(encoding='UTF-8')
# '<mytag>\n</mytag>' # Where's the encoding?
Run Code Online (Sandbox Code Playgroud)
即使我创建了这样的汤BeautifulStoneSoup(fromEncoding='UTF-8'),仍然没有<?xml?>标签。
有没有另一种方法可以在不直接创建和传递标签作为字符串的情况下获取该标签,还是唯一的方法?
我遇到了Borg的设计并且认为它适合我正在做的事情,但是我正在DeprecationWarning使用它(我现在使用的是Python 2.6,但很快就会转向更新的版本).
评论中的新版本是:
class Borg(object):
_state = {}
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls._state
return self
Run Code Online (Sandbox Code Playgroud)
但是,在使用参数创建实例时,会给出DepricationWarning:
DepricationWarning: object.__new__() takes no parameters
Run Code Online (Sandbox Code Playgroud)
有没有办法使用Borg设计而不使用object.__new__()参数?
python ×8
clojure ×1
django ×1
file-io ×1
python-2.x ×1
rust ×1
sublimetext ×1
sublimetext2 ×1