小编Alg*_*bra的帖子

类对象属性的`get_context_data`

get_context_data类对象的属性的。

PasswordContextMixindjango / contrib / auth / views.py中遇到

class PasswordContextMixin:
    extra_context = None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'title': self.title,
            **(self.extra_context or {})
        })
        return context
Run Code Online (Sandbox Code Playgroud)

我感到困惑context = super().get_context_data(**kwargs),因为它等于context = object.get_context_data(**kwargs)

 In [15]: getattr(object, 'get_context_data')
AttributeError: type object 'object' has no attribute 'get_context_data'
Run Code Online (Sandbox Code Playgroud)

如何理解呢?

python django

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

sys.stdout.writelines("hello") 和 sys.stdout.write("hello")

下面两个命令有什么区别?

In [57]: sys.stdout.writelines("hello")                                                                           
hello
In [58]: sys.stdout.write("hello")                                                                                
Out[58]: hello5
Run Code Online (Sandbox Code Playgroud)

python python-3.x

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

在循环中应用`lambda`和`map`?

我有文件命名为:

'guess-number.py', 'convert-object-to-dict.py'
Run Code Online (Sandbox Code Playgroud)

我将它们重命名为:

import os
import glob
py_files = glob.glob('*.py')
Run Code Online (Sandbox Code Playgroud)

然后重命名它们:

for file in py_files:
    os.rename(file, file.replace('-','_'))

or
des_py_file = [file.replace('-','_') for file in py_file ]
for i, j in zip(py_files, dst_py_files:
    os.rename(i,j)
Run Code Online (Sandbox Code Playgroud)

或者,我尝试用lambda和编程函数式编程 map

map(lambda i,j:os.rename(i,j),zip(py_files,dst_py_files))
or 
map(lambda i: os.rename(i, i.replace('-','_')),py_files)
Run Code Online (Sandbox Code Playgroud)

Nothings发生在目录中的文件中,而输出:

<map object at 0x109b237f0>
<map object at 0x109b23d30>
Run Code Online (Sandbox Code Playgroud)

怎么做lambda

python python-3.x

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

在命令echo之后使用quote

我遇到了一个小脚本:

$ for i in *.sh; do echo "$i"; done
name with space.sh
name_with_dash.sh
Run Code Online (Sandbox Code Playgroud)

当我不引用时$i,它会产生相同的结果.

$ for i in *.sh; do echo $i; done
name with space.sh
name_with_dash.sh
Run Code Online (Sandbox Code Playgroud)

我可以看到如何"$i"可能需要被引用为老式的命令状test [ ],cdrm.是否有必要使用引号echo

bash

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

尝试在详细信息视图中覆盖模板名称时的TemplateDoesNotExist

我正在关注django 2.0教程"2.6.2使用通用视图:更少代码更好"并尝试将函数视图转换为类视图.

它抛出这样一个错误:

TemplateDoesNotExist at /polls/1/results/
polls/question_detail.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/polls/1/results/
Django Version: 2.0.4
Run Code Online (Sandbox Code Playgroud)

我用官方资料检查了代码

class ResultsView(generic.DetailView):
    model = Question
    template = 'polls/results.html'

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        #Redisplay the question voting form
        return render(request, 'polls/detail.html', {
            'question':question,
            'error_message':"You did'nt select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
Run Code Online (Sandbox Code Playgroud)

当我尝试提交投票时发生错误:

在此输入图像描述

polls/detail.html随附函数视图时,模板正常工作:

<h1>{{ question.question_text }}</h1>

{% if error_message %}
  <p>
    <strong>{{ error_message }}</strong>
  </p>
{% endif …
Run Code Online (Sandbox Code Playgroud)

python django

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

将 `print` 的输出直接复制到剪贴板

inspect.getsource用来检查我导入的库:

In[52]: from django.views.generic import View
In[53]: view_code = inspect.getsource(View)
In[54]: len(view_code)
Out[54]: 3242
Run Code Online (Sandbox Code Playgroud)

检索格式化代码

In[55]: print(view_code)

class View(object):
    """
    Intentionally simple parent class for all views. Only implements
    dispatch-by-method and simple sanity checking.
    """

    http_method_names = ['get', 'post', 'put',
                        'patch', 'delete', 'head', 'options', 'trace']

    def __init__(self, **kwargs):
Run Code Online (Sandbox Code Playgroud)

我想将代码存储到我的笔记中以供进一步参考,
为此,我必须滚动浏览整个代码以进行复制。
代码太长就不方便了。

如何print以直接的方式将 的输出复制到剪贴板?

python ipython

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

多个try-except没有exec()解决方案

我有这样的多次尝试 - 除外

errors_log = set()
try:
    page_element = chrome.find_element_by_link_text("Next Page")
except Exception as e:
    errors_log.add(e)
try:
    page_element = chrome.find_element_by_class_name("pager_next")
except Exception as e:
    errors_log.add(e)
Run Code Online (Sandbox Code Playgroud)

根据其他问题的答案,我重构代码:

page_elements = ['chrome.find_element_by_link_text("Next Page")',
                 'chrome.find_element_by_class_name("pager_next")',]
for page_element in page_elements:
    try:
        exec(page_element)
    except Exception as e:
       errors_log.add(e) 
Run Code Online (Sandbox Code Playgroud)

我觉得很糟糕,可能是因为使用 exec()

我怎么能重构它不难看?


感谢Zakharov的有用答案,我将代码重构为

actions = [chrome.find_element_by_class_name,
           chrome.find_element_by_link_text]
next_pages = ["pager_next ", "Next Page"]  
prev_pages = ["pager_prev ", "Prev Page"]

def get_page_element_by_multiple_tries(actions, pages):
    """
    Try different context.
    """
    for action, page in zip(actions, pages):
        try:
            page_element = action(page) …
Run Code Online (Sandbox Code Playgroud)

python

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

查找 = strchr(st, '\n'); 替换为 *find = '\0';

我读了C Primer Plus中的一段代码,并努力理解*find = '\0';

#include <stdio.h>
#include <string.h>

char *s_gets(char *st, int n);

struct book {
    char title[40];
    char author[40];
    float value;
}

int main(void) {
    ...
}

char *s_gets(char *st, int n) {
    char *ret_val;
    char *find;

    ret_val = fgets(st, n, stdin);
    if (ret_val) {
        find = strchr(st, '\n'); //look for newline
        if (find)                // if address is not null
            *find = '\0';        //place a null character there
        else
            while (getchar() != '\n')
                continue;  //dispose rest …
Run Code Online (Sandbox Code Playgroud)

c strchr

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

检索有关&& x的信息,该信息保留&x的地址

我想用以下代码探索指针的专长:

#include <stdio.h>
int x = 3;
int main(void)
{
    printf("x's value is %d, x's address is %p", x, &x);
    //printf("x's address is stored in", &&x);
}
Run Code Online (Sandbox Code Playgroud)

它工作正常并获得输出

$ ./a.out
x's value is 3, x's address is 0x10b1a6018
Run Code Online (Sandbox Code Playgroud)

当我利用时&x,为它保留一个存储空间以保持地址0x10b1a6018,因此打印一个地址.

接下来,我打算获取有关存储另一个地址的地址的信息.

#include <stdio.h>
int x = 3;
int main(void)
{
    printf("x's value is %d, x's address is %p", x, &x);
    printf("x's address is stored in", &&x);
}
Run Code Online (Sandbox Code Playgroud)

但它报告错误为:

$ cc first_c_program.c 
first_c_program.c:14:40: warning: data argument not used by format …
Run Code Online (Sandbox Code Playgroud)

c

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

有什么作用?意思是(插入“你好”?\s“世界”?\n)

函数 insert 的示例演示为:

(with-temp-buffer
  (insert "hello" ?\s "world" ?\n)
  (buffer-string))
Run Code Online (Sandbox Code Playgroud)

?这里是什么意思?

syntax emacs elisp character

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

标签 统计

python ×6

c ×2

django ×2

python-3.x ×2

bash ×1

character ×1

elisp ×1

emacs ×1

ipython ×1

strchr ×1

syntax ×1