相关疑难解决方法(0)

如何通过引用传递变量?

Python文档似乎不清楚参数是通过引用还是值传递,以下代码生成未更改的值'Original'

class PassByReference:
    def __init__(self):
        self.variable = 'Original'
        self.change(self.variable)
        print(self.variable)

    def change(self, var):
        var = 'Changed'
Run Code Online (Sandbox Code Playgroud)

有什么我可以通过实际参考传递变量吗?

python reference parameter-passing pass-by-reference

2480
推荐指数
22
解决办法
124万
查看次数

Python有匿名类吗?

我想知道Python是否有类似C#匿名类的功能.为了澄清,这是一个示例C#片段:

var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
Run Code Online (Sandbox Code Playgroud)

在Python中,我会想象这样的事情:

foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar  # true
Run Code Online (Sandbox Code Playgroud)

具体要求是能够在表达式上下文中创建具有指定字段的对象(例如,在lambda和其他不允许语句的地方可用),没有额外的外部声明,并且能够通过普通成员按名称访问各个组件访问语法foo.bar.创建的对象还应该按组件名称 (而不是按位置,如元组那样)实现结构比较.

特别是:元组不是因为它们的组件没有命名; 课程不是因为它们需要声明; dicts不是因为他们有不受欢迎的foo["bar"]语法来访问组件.

namedtuple不是它,因为即使你定义内联类型它仍然需要一个名称,并且比较是基于位置的,而不是基于名称的.特别是:

 def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
 def bar(): return namedtuple("Foo", "y x")(x = …
Run Code Online (Sandbox Code Playgroud)

python

66
推荐指数
6
解决办法
4万
查看次数

理解Python的传递函数参数的逐个调用样式

我不确定我是否通过传递函数参数的对象样式理解Python调用的概念(在此处解释http://effbot.org/zone/call-by-object.htm).似乎没有足够的例子来澄清这个概念(或者我的google-fu可能很弱!:D)

我写了这个有点人为的Python程序,试图理解这个概念

def foo( itnumber, ittuple,  itlist, itdict   ):
    itnumber +=1 
    print id(itnumber) , itnumber 

    print id(ittuple)  , ittuple

    itlist.append(3.4)
    print id(itlist)   , itlist

    itdict['mary']  = 2.3
    print id(itdict),    itdict



# Initialize a number, a tuple, a list and a dictionary
tnumber = 1
print id( tnumber ), tnumber 

ttuple  = (1, 2, 3)
print id( ttuple ) , ttuple

tlist   = [1, 2, 3]
print id( tlist ) , tlist

tdict = tel = {'jack': 4098, 'sape': …
Run Code Online (Sandbox Code Playgroud)

python function

13
推荐指数
3
解决办法
7989
查看次数