小编Chr*_*roa的帖子

在类上覆盖 dict()

我正在尝试dict在 Python 中创建一个类似的类。

当你创建一个类时,你有一些方法告诉 Python 如何创建一个内置类。例如,__int__如果用户int()在类的实例上使用,覆盖该方法会告诉 Python 返回什么。对于__float__. 您甚至可以通过覆盖该__iter__方法来控制 Python 如何生成类的可迭代对象(这可以帮助 Python生成类的lists 和tuples)。我的问题是你如何告诉 Python 如何制作dict你的自定义类?没有什么特别的__dict__方法,你会怎么做呢?我想要类似以下内容:

class Foo():
    def __dict__(self):
        return {
            'this': 'is',
            'a': 'dict'
        }

foo = Foo()
dict(foo) # would return {'this': 'is', 'a': 'dict'}
Run Code Online (Sandbox Code Playgroud)

我试过让类继承自dict,但由于子类试图继承自dictand type,因此在代码中稍后会引发错误,因此继承自dict是不可能的。有没有其他方法可以做到?

此外,我已经覆盖了该__iter__方法,以便它返回一个dict_keyiterator对象(iter()在 a 上使用时返回的内容dict),但它似乎仍然无法正常工作。

python dictionary iterator overriding python-3.x

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

如何仅从Keras提供的MNIST数据集中选择特定数字?

我目前正在使用Keras在MNIST数据集上训练前馈神经网络。我正在使用以下格式加载数据集

(X_train, Y_train), (X_test, Y_test) = mnist.load_data()

但是我只想用数字0和4训练我的模型,而不是全部。如何只选择2位数字?我对python相当陌生,可以弄清楚如何过滤mnist数据集...

python filter mnist deep-learning keras

4
推荐指数
2
解决办法
3201
查看次数

Google云端硬盘API在上传时返回404

我正在尝试通过创建XMLHttpRequest使用Google Drive v3 API将数据上传到文件中。

我使用文件选择器API,返回“0BzAI5S8IJebrUnQtYWFSVzhPdVk”获取文件的ID,以便上载URL应该是“ https://www.googleapis.com/upload/drive/v3/files/0BzAI5S8IJebrUnQtYWFSVzhPdVk?uploadType=resumable ” 。

在我发出PUT请求之后,它返回404状态代码,其中“ Not Found”作为responseText。

我以前尝试过,它会返回状态200,并且能够从响应中获取Location标头,但是现在我无法从任何文件中获取200状态代码。

这是我的代码:

// Log the user in using attachClickHandler (https://developers.google.com/identity/sign-in/web/reference#googleauthattachclickhandlercontainer-options--onsuccess-onfailure)

var id = "0BzAI5S8IJebrOFVMTU5Od183Q2M";
var access_token = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;

var xhr = new XMLHttpRequest();

xhr.open('PUT', 'https://www.googleapis.com/upload/drive/v3/files/' + id + '?uploadType=resumable');
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);

xhr.onreadystatechange = function() {
    if (this.readyState == 4) console.log(this.status);
};
xhr.send();
Run Code Online (Sandbox Code Playgroud)

无论我选择哪个文件,它始终会输出404作为状态代码。我会按照https://developers.google.com/drive/v3/web/resumable-upload上的说明进行操作,但是却没有提及为什么会收到404响应。有什么帮助吗?

javascript xmlhttprequest http-status-code-404 google-drive-api

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