小编cod*_*321的帖子

使用一个函数来获取函数或常规属性的getattr

我有以下代码:

In [38]: %paste
def set_session_attribute(obj, attribute):
    if attribute.endswith('()'):
        attribute = attribute.replace('()', '')
        return getattr(obj, attribute)()
    else:
        return getattr(obj, attribute)


class Thing(object):
    def __init__(self):
        self.legs = 4
    def length(self):
        return 6

## -- End pasted text --

In [39]: x = Thing()

In [40]: y = set_session_attribute(x, 'legs')

In [41]: y
Out[41]: 4

In [42]: z = set_session_attribute(x, 'length()')

In [43]: z
Out[43]: 6
Run Code Online (Sandbox Code Playgroud)

这是因为调用"length()"不起作用(AttributeError, no attribute length())

是否有一种更短,更易于维护的方式来制作这样的功能?谢谢.

python getattr python-3.x getattribute

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

多次更新/删除后,Google Cloud Storage文件卡在时间上

我有一个及时冻结的云存储文件,不会让步。到目前为止,我有:

  • 重新收集了静态文件(Django)并进行了rsync更新

  • 删除有问题的静态文件,重新收集静态文件并进行rsync更新

  • 删除了云存储控制台中的文件并重新同步

  • 删除整个存储桶,并创建另一个具有相同名称的存储桶,然后再次将所有85个静态文件同步到该存储桶

头几次,我更改了静态文件,收集了它们,并进行了同步,它立即起作用。现在我有这条线

var URL = "http://%/api/recipes/delete/&/".replace("%", API_BASE).replace("&", recipe_id);
Run Code Online (Sandbox Code Playgroud)

卡在时间上,冻结在这个桶里。在Django中,我的文件正确读取

var URL = "/api/recipes/delete/&/".replace("&", recipe_id);
Run Code Online (Sandbox Code Playgroud)

更改签入git。

此存储API根本没有更新,即使删除了文件,文件仍在提供中。删除整个存储桶后,文件仍在提供服务,这似乎是一个错误。该文件是:

http://storage.googleapis.com/homebrew-api-static-bucket/static/main/index.js

但是,如果我从Cloud Storage控制台查看文件,则会得到正确的文件。

因此,即使文件桶中的文件正确无误,但我的应用使用的文件在2个多小时后仍然过时

我以以下方式提供文件index.html

<script src="{% static "main/index.js" %}" type='text/javascript'></script>
Run Code Online (Sandbox Code Playgroud)

settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATIC_URL = 'http://storage.googleapis.com/homebrew-bucket/static/'
Run Code Online (Sandbox Code Playgroud)

即使删除和重新制作整个存储桶也不会改变任何东西,我还是没有主意。

python django google-cloud-storage google-cloud-platform

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

-bash:!/ usr/bin/env:找不到事件

我收到了这个奇怪的错误消息,试图将shebang写入python脚本:

$ echo "#!/usr/bin/env python" > scripts/sandbox.py 
-bash: !/usr/bin/env: event not found

$ echo "say what?" > scripts/sandbox.py
Run Code Online (Sandbox Code Playgroud)

立刻,做同样的事情,但没有使用shebang线工程.这种行为是什么以及如何克服?谢谢

python linux macos bash echo

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

干净的方式去os.walk一次python

我想谈谈几个目录,然后抓住一个目录的信息.目前我使用:

i = 0
for root, dirs, files in os.walk(home_path):
    if i >= 1:
        return 1
    i += 1
    for this_dir in dirs:
       do stuff
Run Code Online (Sandbox Code Playgroud)

当然,这非常繁琐.当我想走下它下面的子目录时,我使用j等做同样的5行...

在python中获取单个目录下所有目录和文件的最短方法是什么?

python os.path

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

为什么类型检查对返回的类型不起作用?

我只是试图测试:

if type(model_lines) == 'str':
    turn into a list using split
Run Code Online (Sandbox Code Playgroud)

基于:

In [196]: type('a')
Out[196]: str
Run Code Online (Sandbox Code Playgroud)

然而,对于 x,一个字符串:

In [193]: if type(x) == 'str':
    print 'string'
   .....:  

In [195]: if type(x) == type('a'):
    print 'string'
   .....:     
string
Run Code Online (Sandbox Code Playgroud)

我很好奇为什么我不能使用这个输出来检查类型,它看起来更清晰,阅读速度更快。类型实际上返回什么不允许通过其返回显示进行检查?

python typechecking python-internals

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

什么是检查类型(datetime.date)python的最快方法

我正在为datetime.date检查类型的麻烦.我不知道获得好的类型检查是否是python中的麻烦或者是否有我遗漏的东西:

In [14]: type(datetime.date)
Out[14]: type

In [15]: type(d)
Out[15]: datetime.date

In [16]: arbitrary = datetime.date(1990, 1, 1)

In [17]: type(arbitrary)
Out[17]: datetime.date
Run Code Online (Sandbox Code Playgroud)

我想要比__init__每次都要制作假日期更简单的东西

import datetime

class Month(object):

    def __init__(self, dateobj):
        if type(dateobj) == the type of datetime.date:
            we're good
        else:
            raise Exception('Please feed me a dateobj')
Run Code Online (Sandbox Code Playgroud)

检查这些类型的最快方法是什么,因为基类的类型通常返回无用的类型type.谢谢

python datetime python-3.x

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

在mac-OSError上安装virtualenvwrapper:[Errno 1]不允许操作:

我尝试在Mac上安装virtualenvwrapper并获得经典的python catch 22:

C02QPBHWFVH3MBP:~ ckc3153$ pip install virtualenvwrapper
Collecting virtualenvwrapper
  Using cached virtualenvwrapper-4.7.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.7/site-packages (from virtualenvwrapper)
Requirement already satisfied (use --upgrade to upgrade): virtualenv-clone in /Library/Python/2.7/site-packages (from virtualenvwrapper)
Collecting stevedore (from virtualenvwrapper)
  Using cached stevedore-1.17.1-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade): pbr>=1.6 in /Library/Python/2.7/site-packages (from stevedore->virtualenvwrapper)
Collecting six>=1.9.0 (from stevedore->virtualenvwrapper)
  Using cached six-1.10.0-py2.py3-none-any.whl
Installing collected packages: six, stevedore, virtualenvwrapper
  Found existing installation: six 1.4.1
    DEPRECATION: Uninstalling a distutils installed project …
Run Code Online (Sandbox Code Playgroud)

python macos virtualenv virtualenvwrapper python-2.7

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

在 React 的输入中传递事件和参数 onChange

我有一个组件如下:

import React from 'react';

import MyComponent from '../utils/MyComponent';


export default class BasicList extends MyComponent {

    constructor(props) {
        let custom_methods = [
            'renderItemOrEditField', 'toggleEditing', 'moveCaretAtEnd',
            'editItem'
        ];
        super(props, custom_methods);
        this.state = {
            editing: null,
            current_text: ''
        };
    }

    // moveCaretAtEnd(e) {
    //     var temp_value = e.target.value
    //     e.target.value = ''
    //     e.target.value = temp_value
    // }

    editItem(event) {
        let current_value = event.target.value;
        alert(current_value + this.state.editing);
    }

    renderItemOrEditField(item) {
        console.log(item);
        if (this.state.editing === item.id) {
            return (
                <input
                  onKeyDown={ this.handleEditField } …
Run Code Online (Sandbox Code Playgroud)

html javascript reactjs

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

终端在尝试进行git提交时意外运行命令

我们正在尝试编写一个基于提交历史记录发布文章的脚本.我们运行以下命令而不是进行提交,它实际上将我们放入了一个python终端;

cchilders:~/blogplish (master) 
$ git commit -m "You can run this file using the `python` command in your terminal:\n```$ python blogplish.py\nThe script is working.```"
Python 2.7.12 (default, Jul  1 2016, 15:12:24) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Run Code Online (Sandbox Code Playgroud)

我们很好奇它为什么这样做,上面命令中的两个蟒蛇中的哪一个引起了这个问题.另外,当我们提交这样的提交时,我们如何防止这种情况.我们的脚本将生成的目标语言是markdown.谢谢!

python git shell ubuntu

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

使用 ng-bootstrap 的模板解析错误

我收到错误

Uncaught Error: Template parse errors:
There is no directive with "exportAs" set to "ngbAccordion" ("
    <p *ngIf="spinner" class="text-center margin-100">Loading...</p>

    <ngb-accordion [ERROR ->]#acc="ngbAccordion" activeIds="ngb-panel-0">
      <ngb-panel title="Simple">
        <ng-template "): ng:///SurveysModule/SurveysComponent.html@4:19
'ngb-panel' is not a known element:
1. If 'ngb-panel' is an Angular component, then verify that it is part of this module.
2. If 'ngb-panel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

    <ngb-accordion #acc="ngbAccordion" activeIds="ngb-panel-0">
      [ERROR ->]<ngb-panel title="Simple">
        <ng-template ngbPanelContent> …
Run Code Online (Sandbox Code Playgroud)

javascript ng-bootstrap angular

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