小编ale*_*lex的帖子

我可以将类方法和默认参数传递给另一个类方法

我想将类方法作为默认参数传递给另一个类方法,以便我可以将该方法重用为@classmethod:

@classmethod
class foo:
    def func1(self,x):
        do somthing;
    def func2(self, aFunc = self.func1):
        # make some a call to afunc
        afunc(4)
Run Code Online (Sandbox Code Playgroud)

这就是为什么在func2aFunc默认情况下调用该方法的原因self.func1,但是我可以从类外部调用这个相同的函数,并在输入处传递一个不同的函数.

我明白了:

NameError:未定义名称"self"

这是我的设置:

class transmissionLine:  
    def electricalLength(self, l=l0, f=f0, gamma=self.propagationConstant, deg=False):  
Run Code Online (Sandbox Code Playgroud)

但我希望能够electricalLength使用不同的函数调用gamma,例如:

transmissionLine().electricalLength (l, f, gamma=otherFunc)
Run Code Online (Sandbox Code Playgroud)

python class

6
推荐指数
1
解决办法
3506
查看次数

测试 @classmethod 函数的现有属性,产生 AttributeError

我有一个函数,它是一个类方法,我想测试该类的一个属性,该属性可能是也可能不是 None,但将始终存在。

class classA():
 def __init__(self, var1, var2 = None):
  self.attribute1 = var1
  self.attribute2 = var2

 @classmethod
 def func(self,x):
  if self.attribute2 is None:
   do something  
Run Code Online (Sandbox Code Playgroud)

我得到了错误

AttributeError: class classA has no attribute 'attributeB'
Run Code Online (Sandbox Code Playgroud)

当我像我展示的那样访问属性时,但如果在命令行上我可以看到它有效,

x = classA()
x.attribute2 is None 
True
Run Code Online (Sandbox Code Playgroud)

所以测试有效。

如果我@classmethod从 中删除装饰器func,问题就会消失。
如果我离开@classmethod装饰器,它似乎只会影响在超类的构造函数中提供默认值的变量。

上面的代码是怎么回事?

python variables class

3
推荐指数
1
解决办法
2638
查看次数

将print的输出分配给python中的变量

我想知道如何将print的输出分配给变量.

因此,如果

mystring = "a=\'12\'"
Run Code Online (Sandbox Code Playgroud)

然后

print mystring 
a=12
Run Code Online (Sandbox Code Playgroud)

我想像**kwargs一样传递这个

test(mystring)
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

更多解释:我有一个从数据文件的注释行获得的字符串列表.它看起来像这样:

"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
 "a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'",
 '']
Run Code Online (Sandbox Code Playgroud)

我想把这些值放到某个结构中,这样我就可以绘制各种不同的变量,所以列表基本上是一个图例,我想绘制轨迹的函数与传奇中给出的变量.

因此,如果对于每个条目我有一个跟踪,那么我可能想要为一系列值绘制max(trace)vs offX.

我的第一个想法是将字符串作为**kwargs传递给一个能产生相应数据矩阵的函数.

python

2
推荐指数
1
解决办法
9154
查看次数

标签 统计

python ×3

class ×2

variables ×1