我试图理解Python中的Iterability.
据我所知,__iter__()
应该返回一个next()
定义了方法的对象,该对象必须返回一个值或引发StopIteration
异常.因此,我写了这个满足这两个条件的课程.
但它似乎没有用.怎么了?
class Iterator:
def __init__(self):
self.i = 1
def __iter__(self):
return self
def next(self):
if self.i < 5:
return self.i
else:
raise StopIteration
if __name__ == __main__:
ai = Iterator()
b = [i for i in ai]
print b
Run Code Online (Sandbox Code Playgroud) 好像__getattribute__
只有2个参数(self, name)
.
但是,在实际代码中,我拦截的方法实际上是参数.
反正有没有访问这些论点?
谢谢,
查理
我是python的新手,我想要一些帮助.我创建了一些带有属性的类,以防止我传递毫无意义的参数.
所以我举了这个课
class match(object):
__teams=(None,None)
def setTeams(self,tms):
if type(tms) != type(list()) and type(tms) != type(tuple()):
raise Exception("Teams must be a list of length 2")
if len(tms) != 2:
raise Exception("Teams must be a list of length 2")
if (type(tms[0])==type(str()) or (type(tms[0])==type(unicode()))) \
and (type(tms[1])==type(str()) or type(tms[1])==type(unicode())):
self.__teams=tms
else:
raise Exception("Both teams must be strings")
return
teams=property(getTeams,setTeams)
Run Code Online (Sandbox Code Playgroud)
如果我写
match1=match()
match1.teams=(2,4)
Run Code Online (Sandbox Code Playgroud)
我应该得到一个例外,但是
match1.teams[0]=5
Run Code Online (Sandbox Code Playgroud)
不会引发异常并传递数字5.请记住,这不是全部类,我只记下了与我的问题相关的内容,所以假设代码的行为和我描述的一样.
我想这是因为所有内容都是通过python中的引用传递的,但是我必须小心不要将无意义的数据分配给我的对象,这首先会破坏了拥有属性的目的.
那么,有没有办法解决这个问题,除了不使用列表或我是否必须学会使用它?
我正在使用的python描述符是在其所有者类的所有实例之间共享其值.如何使每个实例的描述符包含其自己的内部值?
class Desc(object):
def __init__(self, initval=None,name='val'):
self.val = initval
self.name = name
def __get__(self,obj,objtype):
return self.val
def __set__(self,obj,val):
self.val = val
def __delete__(self,obj):
pass
class MyClass(object):
desc = Desc(10,'varx')
if __name__ == "__main__":
c = MyClass()
c.desc = 'max'
d = MyClass()
d.desc = 'sally'
print(c.desc)
print(d.desc)
Run Code Online (Sandbox Code Playgroud)
输出为this,最后一次调用设置两个对象的值:
localhost $ python descriptor_testing.py
sally
sally
Run Code Online (Sandbox Code Playgroud) 为什么以下代码给出"无"?我该如何解决这个问题?
def f1(list1):
f2(list1.append(2))
def f2(list1):
print(list1)
f1([1])
Run Code Online (Sandbox Code Playgroud)
什么也行不通:
def f1(list1):
arg1 = list1.append(2)
f2(arg1)
Run Code Online (Sandbox Code Playgroud) 签名map
是
map(function, iterable[, iterables[, ...]])
Run Code Online (Sandbox Code Playgroud)
在Python 2.x中假设function
是None
身份,并且短迭代用'None'填充到最长迭代的长度.
在Python 3.x中,如果function
是None
你最终得到一个异常:
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)
并且所有迭代都被修剪到最短的长度.
这是一些非常激烈的变化.我如何获得2.x语义?
哦,它现在返回一个迭代器而不是一个列表,但我没关系.;)
这对于你事先不知道将应用哪个函数(如果有的话)的情况很有用 - 只是因为你实际上没有转换迭代并不意味着你不想要它的内容.
我有一个列表,.dbf
其中包含我想要更改为.csv
文件的文件.我用excel手动打开它们并重新保存它们.csv
,但这需要花费太多时间.
现在我创建了一个更改文件名的脚本,但是当我打开它时,它仍然是一个.dbf
文件类型(虽然它被调用.csv
).如何以文件类型也发生变化的方式重命名文件?
我的脚本使用(dbf和csv文件名列在单独的csv文件中):
IN = dbffile name
OUT = csvfile name
for output_line in lstRename:
shutil.copyfile(IN,OUT)
Run Code Online (Sandbox Code Playgroud) 我正在处理一些报告(计数),我必须获取不同参数的计数.很简单,但很乏味.
一个参数的示例查询:
qCountsEmployee = (
"select count(*) from %s where EmployeeName is not null"
% (tablename)
)
CountsEmployee = execute_query(qCountsEmployee)
Run Code Online (Sandbox Code Playgroud)
现在我有几百个这样的参数!
我所做的是:创建所有参数的列表并使用快速Python脚本生成它们,然后复制该文本并将其放在主脚本中以避免繁琐的线条.
columnList = ['a', 'b', ............'zzzz']
for each in columnList:
print (
'q' + each + ' ='
+ '"select count(*) from %s where' + each
+ 'is not null" % (tablename)'
)
print each + ' = execute_query(' + 'q' + each + ')'
Run Code Online (Sandbox Code Playgroud)
虽然这种方法有效,但我想知道如果不是单独的脚本来生成代码行并将粘贴复制到主程序中,我是否可以直接在主脚本中生成它们并让脚本将它们视为代码行?这将使代码更具可读性是我的想法.希望我有道理!谢谢...
寻找有关此代码引发的原因的详细解释SyntaxError
.
def echo(x):
return x
def foo(s):
d = {}
exec(s, {}, d)
return dict((x,y) for x,y in d.items())
def bar(s):
d = {}
exec(s, {}, d)
return dict((x, echo(y)) for x,y in d.items()) # comment this to compile
s = 'a=1'
foo(s)
Run Code Online (Sandbox Code Playgroud)
File "test.py", line 11
exec(s, {}, d)
SyntaxError: unqualified exec is not allowed in function 'bar' it contains a
nested function with free variables
Run Code Online (Sandbox Code Playgroud) 我将尝试简化这里的情况,当覆盖__new__
如下时,我不知道调用 super__new__
来完成这项工作的正确方法,我做得好吗还是有其他方法可以做到这一点?
super().__new__(cls)
没有产生我预期的正确结果
我是 python 初学者,请耐心等待,我很流利 C++
import weakref
class A(str):
def __init__(self,s):self.a=s
class B(str):
def __init__(self,s):self.b=s
class P(A,B):
manifest=weakref.WeakValueDictionary()
def __new__(cls,a,b):
o=P.manifest.get(a+b)
if not o:
print(a,b,super(P,cls))
#i thought this first should be used because __init__ puts the values in
#and we index the manifest with parameters [a+b]
#o=super().__new__(cls)#produces unique results for all requests?!?
#so i called like this and it works (either with a or b)
o=super().__new__(cls,a)#why favoring a over b?
#o=super().__new__(cls,b)#why favoring b …
Run Code Online (Sandbox Code Playgroud) python ×9
python-3.x ×3
class ×1
csv ×1
dbf ×1
descriptor ×1
dynamic ×1
excel ×1
iterator ×1
list ×1
properties ×1
rename ×1