我是python的新手,我希望我能用.符号来访问a的值dict.
让我们说我test喜欢这样:
>>> test = dict()
>>> test['name'] = 'value'
>>> print(test['name'])
value
Run Code Online (Sandbox Code Playgroud)
但是,我希望我能做到test.name让value.事实上,我通过覆盖__getattr__我的类中的方法来做到这一点:
class JuspayObject:
def __init__(self,response):
self.__dict__['_response'] = response
def __getattr__(self,key):
try:
return self._response[key]
except KeyError,err:
sys.stderr.write('Sorry no key matches')
Run Code Online (Sandbox Code Playgroud)
这很有效!当我做:
test.name // I get value.
Run Code Online (Sandbox Code Playgroud)
但问题是当我test单独打印时,我得到的错误是:
'Sorry no key matches'
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
如何使用类型提示来注释返回一个Iterable总是产生两个值的函数:a bool和a str?提示Tuple[bool, str]很接近,除了它将返回值类型限制为元组,而不是生成器或其他类型的可迭代.
我很好奇,因为我想注释一个foo()用于返回多个值的函数,如下所示:
always_a_bool, always_a_str = foo()
Run Code Online (Sandbox Code Playgroud)
通常函数喜欢foo()做这样的事情return a, b(它返回一个元组),但我喜欢的类型暗示有足够的灵活性,以取代发电机或列表或别的东西返回的元组.
from collections import namedtuple
Point = namedtuple('whatsmypurpose',['x','y'])
p = Point(11,22)
print(p)
Run Code Online (Sandbox Code Playgroud)
输出:
whatsmypurpose(x=11,y=22)
Run Code Online (Sandbox Code Playgroud)
什么是相关性/用途'whatsmypurpose'?
是否有可能从元组中获得价值:
TUPLE = (
('P', 'Shtg1'),
('R', u'Shtg2'),
('D', 'Shtg3'),
)
Run Code Online (Sandbox Code Playgroud)
通过调用STR键就好 P
Python说只有int才能用于这种类型的'查询'
我不能使用循环(开销太大......)
谢谢!
有时候我需要在python中创建一个匿名类实例,就像c#一样:
var o= new {attr1="somehing", attr2=344};
Run Code Online (Sandbox Code Playgroud)
但是在python中我这样做:
class Dummy: pass
o = Dummy()
o.attr1 = 'something'
o.attr2 = 344
#EDIT 1
print o.attr1, o.attr2
Run Code Online (Sandbox Code Playgroud)
如何在单一语句中以pythonic方式做到这一点?
我想知道enum和namedtuple之间有什么区别,以及何时应该使用一个而不是另一个.
我有一个非常基本的问题.
假设我调用一个函数,例如,
def foo():
x = 'hello world'
Run Code Online (Sandbox Code Playgroud)
如何让函数以这样的方式返回x,我可以将它用作另一个函数的输入或者在程序体内使用变量?
当我使用return并在另一个函数中调用该变量时,我得到一个NameError.
与特定类关联的typename有什么用?例如,
Point = namedtuple('P', ['x', 'y'])
Run Code Online (Sandbox Code Playgroud)
你通常会在哪里使用typename'P'?
谢谢!
我想在两个Python程序之间传递对象状态(一个是我自己的独立运行代码,一个是Pyramid视图),以及不同的命名空间.这里或这里有一些相关的问题,但我不能完全按照我的方案进行操作.
我自己的代码定义了一个__main__有点复杂结构的全局类(即命名空间):
# An instance of this is a colorful mess of nested lists and sets and dicts.
class MyClass :
def __init__(self) :
data = set()
more = dict()
...
def do_sth(self) :
...
Run Code Online (Sandbox Code Playgroud)
在某些时候,我挑选了这个类的一个实例:
c = MyClass()
# Fill c with data.
# Pickle and write the MyClass instance within the __main__ namespace.
with open("my_c.pik", "wb") as f :
pickle.dump(c, f, -1)
Run Code Online (Sandbox Code Playgroud)
A hexdump -C my_c.pik表明前几个字节包含__main__.MyClass我假设该类确实在全局命名空间中定义,并且这在某种程度上是读取pickle的要求.现在我想MyClass …
我甚至不确定这些东西是正式调用的,但是,Python有元数据,通常位于模块文件的顶部,例如__version__ = '0.1'.
如何找到PyDoc支持的所有列表?
python ×10
python-3.x ×4
namedtuple ×2
dictionary ×1
enums ×1
function ×1
instance ×1
nested ×1
pickle ×1
pydoc ×1
python-3.5 ×1
tuples ×1
type-hinting ×1
typename ×1