小编Phi*_*per的帖子

为什么在__new__之后没有调用__init__

让我从这开始不重复 为什么__init__如果没有args调用__new__就不会被调用.我试图精心构建了一些示例代码__new____init__有没有解释,我可以找到.

基本参数:

  • 有一个名为NotMine的基类,因为它来自另一个库(我最后会透露,这里不重要)
  • 该类有一个__init__方法,反过来调用一个_parse方法
  • 我需要覆盖_parse子类中的方法
  • 我正在创建的子类直到调用才知道
  • 我知道有工厂设计方法,但我不能在这里使用它们(更多在最后)
  • 我试图小心使用super以避免Python日志记录中的问题 :为什么__init__被调用两次?
  • 我知道这也是一种AbstractBaseMehtod机会,但这并没有帮助

无论如何,__init__应该在之后调用__new__以及为什么下面的一些样本不起作用的每个解释我似乎能够指出其他有用的情况并排除解释.

class NotMine(object):

    def __init__(self, *args, **kwargs):
        print "NotMine __init__"
        self._parse()

    def _parse(self):
        print "NotMine _parse"

class ABC(NotMine):
    def __new__(cls,name,*args, **kwargs):
        print "-"*80
        print "Entered through the front door ABC.__new__(%s,%s,*%s,**%s)"%(cls,name,args,kwargs)
        if name == 'AA':
            obj = super(NotMine,ABC).__new__(AA,*args,**kwargs)
            print "Exiting door number 1 with an instance of: %s"%type(obj)
            return obj 
        elif …
Run Code Online (Sandbox Code Playgroud)

python genshi

10
推荐指数
1
解决办法
5434
查看次数

Python - 如何使用 kwargs 从类创建对象或调用方法

我有以下带有 kwargs init 的父类:

class A(object):
    """ Parent class """
    def __init__(self, **kwargs):     

        # connect parameters
        self.host           = kwargs.get('host', 'localhost')
        self.user           = kwargs.get('user', None)
        self.password       = kwargs.get('password', None)

    def connect(self):
        try:           
            self.ConnectWithCred( self.host, 
                                  self.port, 
                                  self.user,
                                  self.password)
        except pythoncom.com_error as error:
            e = format_com_message("Failed to connect")
            raise Error(e)
Run Code Online (Sandbox Code Playgroud)

我想创建一个“类 A”的对象并调用“连接”方法。我该怎么办?我尝试了以下操作,但它无法运行(仅供参考 - 我是 Python 新手):

sub_B = A(self.host = 'example.com', self.port = 22, self.user = 'root', 
          self.password = 'testing')
sub_B.connect()
Run Code Online (Sandbox Code Playgroud)

python keyword-argument

7
推荐指数
1
解决办法
2301
查看次数

pytest参数化会话固定装置执行太多次

考虑以下测试代码,该代码将模拟运行结果与预期结果进行比较。运行结果的值取决于提供两个值的参数化灯具参数的值,因此运行结果有两种可能的变体。由于它们都是会话固定装置,因此我们应该期望run_result固定装置仅执行两次。

现在,请看一下测试用例test_run_result,它接收run_result和Expected_result夹具进行比较,并且还接收用两个值参数化的公差夹具。测试用例检查预期结果与结果之间的差异是否在公差范围内。注意,运行不取决于公差。

出于某种原因,我不理解Pytest会执行run_result()夹具三次。你能解释为什么吗?

这是使用pytest vers测试的。2.9.1

顺便说一句,如果未对测试用例进行参数化或使用装饰器而不是夹具对参数进行参数化,则run_result夹具将仅执行两次,即:@ pytest.mark.parametrize('tolerance',[1e-8,1e- 11])。

import pytest

runcounter = 0

@pytest.fixture(scope="session", params=[1e-8, 1e-11])
def tolerance(request):
    """Precision in floating point compare."""
    return request.param

@pytest.fixture(scope='session', params=[1, 2])
def paramfixture(request):
    return request.param

@pytest.fixture(scope="session")
def expected_result(paramfixture):
    return 1 + paramfixture

@pytest.fixture(scope='session')
def run_result(paramfixture):
    global runcounter
    runcounter = runcounter + 1
    print "Run #", runcounter, 'param:', paramfixture
    return 1 + paramfixture

def test_run_result(run_result, expected_result, tolerance):
    print "run_result: %d, expected_result: %d" % (run_result, expected_result)
    assert abs(run_result - expected_result) < tolerance
Run Code Online (Sandbox Code Playgroud)

Pytest屏幕截图:

$ py.test …
Run Code Online (Sandbox Code Playgroud)

python pytest

5
推荐指数
1
解决办法
733
查看次数

Clojure Spec Dependent字段

我有一个记录,对于此规范,我想生成值但确保当前金额不超过最大金额.简化的规范将是这样的:

(s/def ::max-amt (s/and number? #(<= 0 % 1e30)))
(s/def ::cur-amt (s/and number? #(<= 0 % 1e30)))
(s/def ::loan (s/cat :max-amt ::max-amt
                     :cur-amt ::cur-amt))
Run Code Online (Sandbox Code Playgroud)

我知道我可以s/and::loan规范中,但我想要的东西:

(s/def :loan (s/cat :max-amt ::max-amt
                    ;; not a real line:
                    :cur-amt (s/and ::cur-amt #(< (:cur-amt %) (:max-amt %)))))
Run Code Online (Sandbox Code Playgroud)

这种类型的约束是否可用于规范?

注意:我知道我可以用0到1之间的数字替换cur-amt,它代表小数部分但是我正在修改数据以适应代码而不是其他方式.我不在这里控制实际应用程序中的数据源.

clojure

5
推荐指数
1
解决办法
556
查看次数

类型推理的Clojure不足

这段代码不是我的"真实"代码,而是来自更大算法的问题示例.在我发现(set! *warn-on-reflection* true)反射是问题之前我花了一段时间.

随着类型提示变为动态语言(例如python和clojure)以及侵略性类型引用传递给其他人(例如Scala),我必须明确地使用(int ...).

为什么clojure不知道(aget int-array int)返回int?

我可以自己注释if语句,说它返回一个int吗?

如果没有,我可以使用内联函数来避免重新感染.

(let [a (int-array [4 5 6 7])]
   ;(aset a 1 (int (if (seq a) 40 (aget a 0))))) ;; fast
    (aset a 1      (if (seq a) 40 (aget a 0))))  ;; slow
Run Code Online (Sandbox Code Playgroud)

我知道类型提示并不比这个int调用更简单,但在更复杂的代码中可能并非如此.

type-inference clojure

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