相关疑难解决方法(0)

你如何使用argparse获取程序的名称?

argparse用来解析命令行参数.在浏览文档时,argparse我只能看到使用不同程序名称的规定.

我希望能够使用默认程序名称而无需导入sys.argparse根据我的意见,没有任何内容会返回程序名称.

import argparse

parser = argparse.ArgumentParser()
args = parser.parse_args()

print(dir(args))
Run Code Online (Sandbox Code Playgroud)

这是输出:

['__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_args', '_get_kwargs']

有没有其他方法可以检索程序名称而无需导入sys模块?

python argparse

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

Python中这个运算符"_"的名称是什么?

我正在阅读Python的隐藏功能,我遇到了这个答案.

从帖子开始:

使用交互式shell时,"_"包含最后打印项的值:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> _
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
Run Code Online (Sandbox Code Playgroud)

这个运营商的名字是什么?我在文档上找不到它,我从未听说过它(以及其他语言).是否值得使用它?

PS.我想知道它的名字,因为我想看看该函数是如何实现的,并搜索其他语言是否具有这个非常棒的功能.

python

12
推荐指数
1
解决办法
2893
查看次数

__test__ =假魔法属性如何用于测试发现

所以我试图实现类似于单元测试框架如何执行以下操作:

class BaseTest(T.TestCase):
    # Disables this test from being run
    __test__ = False

    def test_foo(self): pass


# However this test is picked up because it doesn't directly have __test__ set
class InheritingTest(BaseTest): pass
Run Code Online (Sandbox Code Playgroud)

我觉得奇怪的一件事:

# >> InheritingTest.__test__
# False
Run Code Online (Sandbox Code Playgroud)

这将表明,我认为这是不使用元类设置 __test__True建筑的类型.

我尝试了通过python库,find . -name "*.py" | xargs grep '__test__'但似乎没有发现任何与此相关的内容.

我解决这个问题的"猜测"方法是执行以下操作:

def is_class_tested(cls):
    return cls.__dict__.get('__test__', True)
Run Code Online (Sandbox Code Playgroud)

然而,这对我来说感觉很脆弱......有没有更清洁/更好的方法来做到这一点在所有情况下都有效?班级是否有可能没有__dict__财产?

python

12
推荐指数
1
解决办法
1054
查看次数

什么_和__在PYTHON中意味着什么

当我输入___在python shell中我得到返回的值.例如:

>>> _
2
>>>__
8
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

python

11
推荐指数
2
解决办法
7394
查看次数

如何在django基于类的视图中单元测试方法?

我需要在django基于类的视图中测试方法和辅助函数.

考虑这个基于类的视图:

class MyClassBasedView(View):

    def dispatch(self, request, *args, **kwargs):
        ....

    def __get_render_dict():
        d = {}
        ...
        return d

    def my_method(self):
        render_dict =  self.__get_render_dict()
        return render_response(self.request, 'template.html', render_dict)
Run Code Online (Sandbox Code Playgroud)

为了为我的视图编写单元测试,我需要调用里面的方法,__get_render_dict()直接说.我怎么能实现这个目标?

我试过了

v = MyClassedBasedView() 
v.dispatch(request,args, kwargs)
v.__method_name()
Run Code Online (Sandbox Code Playgroud)

但是在post/get方法中没有匹配的参数失败了,即使我在不​​使用URL的情况下调用方法direclty.

python django unit-testing django-class-based-views

11
推荐指数
3
解决办法
5875
查看次数

在Python中覆盖"私有"方法

考虑使用"私有"方法的类,例如:

class Foo(object):
    def __init__(self):
        self.__method()
    def __method(self):
        print('42')
Run Code Online (Sandbox Code Playgroud)

当我尝试子类化Foo和覆盖方法时__method,可以看到它Foo.__method仍然被调用,而不是MoreFoo.__method.

class MoreFoo(Foo):
    def __method(self):
        print('41')

>>> MoreFoo()
42
<__main__.MoreFoo object at 0x7fb726197d90>
Run Code Online (Sandbox Code Playgroud)

覆盖这种方法的方法是什么?

python oop methods subclass private-members

10
推荐指数
3
解决办法
7861
查看次数

为什么子类在本例中没有从python中的父类继承方法?

我有以下代码.

class Foo(object):
     def __init__(self):
         self.__baz = 40
     def foo(self):
         print self.__baz

class Bar(Foo):
     def __init__(self):
         #super(Bar, self).__init__()
         self.__baz = 21
     def bar(self):
         print self.__baz

x = Bar()
x.foo()
x.bar()
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Traceback (most recent call last):
  File "classes.py", line 15, in <module>
    x.foo()
  File "classes.py", line 5, in foo
    print self.__baz
AttributeError: 'Bar' object has no attribute '_Foo__baz'
Run Code Online (Sandbox Code Playgroud)

为什么这个foo方法没有继承Bar.

编辑:它工作正常,如果你打电话给超级评论.

python oop inheritance

9
推荐指数
1
解决办法
2606
查看次数

在课堂上运行所有功能

我试图在我的课程中运行所有的功能,而不是单独输入它们.

class Foo(object):
    def __init__(self,a,b):
        self.a = a
        self.b=b

    def bar(self):
        print self.a

    def foobar(self):
        print self.b
Run Code Online (Sandbox Code Playgroud)

我想这样做但是有一个循环,因为我的实际类有大约8-10个函数.

x = Foo('hi','bye')
x.bar()
x.foobar()
Run Code Online (Sandbox Code Playgroud)

python class

9
推荐指数
3
解决办法
9696
查看次数

如何在添加到类中的方法中访问"__"(双下划线)变量

背景

我希望使用元类来添加基于原始类的辅助方法.如果我希望添加的方法使用,self.__attributeName我得到一个AttributeError(因为名称修改)但是对于现有的相同方法,这不是问题.

代码示例

这是一个简化的例子

# Function to be added as a method of Test
def newfunction2(self):
    """Function identical to newfunction"""
    print self.mouse
    print self._dog
    print self.__cat

class MetaTest(type):
    """Metaclass to process the original class and
    add new methods based on the original class
    """
    def __new__(meta, name, base, dct):
        newclass = super(MetaTest, meta).__new__(
                meta, name, base, dct
                )

        # Condition for adding newfunction2
        if "newfunction" in dct:
            print "Found newfunction!"
            print "Add newfunction2!"
            setattr(newclass, "newfunction2", newfunction2) …
Run Code Online (Sandbox Code Playgroud)

python metaprogramming class

9
推荐指数
1
解决办法
6245
查看次数

python中的双下划线

class A(object):
    def __get(self):
        pass

    def _m(self):
        return self.__get()


class B(A):
    def _m(self):
        return str(self.__get())

print(A()._m())
print(B()._m())
Run Code Online (Sandbox Code Playgroud)

为什么print(A()._m())打印None,但print(B()._m())加注AttributeError: 'B' object has no attribute '_B__get'

我认为双下划线可以防止方法覆盖.

UPDATE

你写的__get是私人的.

那为什么以下工作呢?

class A(object):
    def __get(self):
        pass

    def _m(self):
        return self.__get()


class B(A):
    pass

print(A()._m())
print(B()._m())
Run Code Online (Sandbox Code Playgroud)

为什么这段代码不会引发AttributeError和打印None两次?

python

9
推荐指数
1
解决办法
3102
查看次数