【Python:从对象获取具有整数名称的属性】教程文章相关的互联网学习教程文章

python – 使用try和except使用属性的正确方法【代码】

我有使用@property装饰器设置属性的类.它们使用try和except子句作为getter和setter.如果未设置attribute,它将从数据库获取数据并使用它来从其他类中实例化对象.我试图保持示例简短,但用于实例化属性对象的代码与每个属性略有不同.他们的共同点是尝试 – 开头时除外.class SubClass(TopClass):@propertydef thing(self):try:return self._thingexcept AttributeError:# We don't have any thing yetpassthing = get_some_thing_from...

python – 将实例列表转换为实例属性列表【代码】

我有一个实例列表,我需要从该列表中提取每个实例的某个属性,这将形成一个新列表.我对Python有些新手,我能解决这个问题的唯一方法是使用exec()函数,这显然使它成为一个可怕的解决方案.有人知道更好的方法吗? 我目前的职能是:def attributelist(list, attribute):"Inputs a list of instances and returns a list of a certain attribute of those instances"output = []for instance in list:exec("output.append(instance." + at...

python – 使用ElementTree在XML文件中设置属性值【代码】

我需要将xml文件中名为approved-by的属性的值从“no”更改为“yes”.这是我的xml文件:<?xml version="1.0" encoding="UTF-8" ?> <!--Arbortext, Inc., 1988-2008, v.4002--> <!DOCTYPE doc PUBLIC "-//MYCOMPANY//DTD XSEIF 1/FAD 110 05 R5//EN""XSEIF_R5.dtd"> <doc version="XSEIF R5" xmlns="urn:x-mycompany:r2:reg-doc:1551-fad.110.05:en:*"><meta-data><?Pub Dtl?><confidentiality class="mycompany-internal" /><doc-na...

python子类调用父类未绑定的属性和方法【代码】

class People:country = 'China'def __init__(self, name, age):self.name = nameself.age = agedef tell_info(self):print('Name is %s, the age is %s'%(self.name, self.age))class People1(People):def __init__(self, name, age, sex, hobby):People.__init__(self, name, age)self.sex = sexself.hobby = hobbydef tell_info(self):People.tell_info(self)print('the gender is %s, the hobby is %s' % (self.sex, self.hobb...

Python属性最佳实践,属性内的一个函数【代码】

拥有属于非常基本操作的属性是一种好习惯吗?例如,假设我们有属性’a’和’b’,我们可以直接从’a’和’b’推断属性’c’.这被认为是不好的编码风格?@property def c(self):return self.a + self.b谢谢!解决方法:即使是非常简单的计算,使用属性的一个好处是,如果a或b发生变化,属性的有效值将自动更新. 例如,如果c不是属性,则每次self.a或self.b更改时都必须更新self.c的值:self.a += 1 self.c = self.a + self.b但如果c是属性,...

python fabric错误’module’对象没有属性’HAVE_DECL_MPZ_POWM_SEC’【代码】

运行结构时出现以下错误(ENV)[root@server-124 ENV]# fab Traceback (most recent call last):File "/usr/bin/fab", line 9, in <module>load_entry_point('Fabric==1.8.3', 'console_scripts', 'fab')()File "/usr/lib/python2.6/site-packages/pkg_resources.py", line 299, in load_entry_pointreturn get_distribution(dist).load_entry_point(group, name)File "/usr/lib/python2.6/site-packages/pkg_resources.py", line 22...

python – Scikit-learn Multicore:“AttributeError:StdIn实例没有属性’close’”【代码】

我正在使用PyCharm从Scikit-learn运行RandomForestRegressor.这在执行整个脚本时工作正常:clf = ensemble.RandomForestClassifier(n_estimators=100, n_jobs = 4, verbose=1, oob_score=True) clf = clf.fit(x_train, y_train)当我尝试从控制台运行该行时,我反复出现此错误:AttributeError: StdIn instance has no attribute 'close'File "/usr/local/Cellar/python/2.7.6_1/Frameworks/Python.framework/Versions/2.7/lib/pytho...

python – NoneType’对象没有属性’model’【代码】

我的一个表格是给我这个错误,我似乎无法弄清楚问题是什么.11:24:04 web.1 | Internal Server Error: /dash/location/add 11:24:04 web.1 | Traceback (most recent call last): 11:24:04 web.1 | File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 114, in get_response 11:24:04 web.1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) 11:24:04 web.1 | Fi...

python – 多处理AttributeError模块对象没有属性’__path__’【代码】

我有一个很长的脚本,最后需要运行一个函数到大型列表的所有项目,这需要很长时间,例如考虑:input_a= [1,2,3,4] # a lengthy computation on some data print('test.1') # for testing how the script runs input_b= [5,6,7,8] # some other computation print('test.2')def input_analyzer(item_a): # analyzing item_a using input_a and input_breturn(item_a * input_a[0]*input_b[2])from multiprocessing import Pool def an...

python – 为什么在枚举中找不到以下属性?【代码】

我使用的是Python 2.7.5,我安装了Enum as 点击安装枚举 我已经写出以下代码来测试Enum.from enum import Enum class Color(Enum):red = 'Hello'blue = 'Trello'green = 'Yello'for name, attr in Color.__members__.items():print(attr.value)这引起了我的错误说法. AttributeError:类型对象’Color’没有属性’__members__’. 为什么python无法获得__members__?解决方法:你把enum和enum混淆了.他们有许多相似之处,但不是一回事....

python – AttributeError:’numpy.ndarray’对象没有属性’items’【代码】

对于以下代码,我收到了标题中的错误:import scipy.io as sio import numpy as nptemp = np.load('temp.npy') sio.savemat('final.mat',temp)尽管AttributeError是python中的常见错误,但我没有找到标题中提到的“items”有用的东西.我们该如何解决这个问题?解决方法:它需要一个dict作为第二个参数而不是数组: 从docs: mdict:dictDictionary from which to save matfile variables.我不太熟悉,但我想你把名称作为键,数组作为值传...

python – 使用self作为外部方法的一个属性是一个好习惯吗?【代码】

我试图让我免于重复两个类中的代码,我已经测试了下面的代码片段并且它有效,我想知道这是一个好的做法还是我应该考虑使用继承.在这种情况下,这种方法有什么特别的错误吗?def do_something_with_self(obj):print 'Hello, I was called from %s' % obj.nameclass A(object):name = "Class A"def do_something(self):do_something_with_self(self) class B(object):name = "Class B"def do_something(self):do_something_with_self...

在Python中,如何从类方法的返回值初始化类属性?【代码】

想象一下,我们有这个课程:class Custom:@classmethoddef get_choices(cls):# use cls attributes to return a listmapping = {"key": ... }我想将get_choices()返回的值与key相关联.应该使用什么代码而不是占位符……? 编辑:我想保持与上下文无关的问题(在我看来,这个要求很常见,但我可能有偏见).正如评论中所建议的那样,我将提供更多细节,因为我们似乎共同关注“最简单的代码”: 我正在开发一个Django应用程序,我希望使用它们...

python – ‘list’对象没有属性’get’【代码】

这是我第一次使用Django rest框架的Web服务. 这就是我的settigngs的样子INSTALLED_APPS = ('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework' )data.py:from rest_framework.views import View from rest_framework.response import Response from rest_framework import statusORDERS = [['0', ...

使用Python模拟模块,我如何修补一个类,以便它只存储我想要存根的方法并单独留下其他属性和方法?【代码】

我想要做的是在一个类中存取一些方法,这些方法在我正在测试的某些代码中间接实例化.我希望修补类的所有其他属性和方法正常运行. 这是一个显示我想要的简单案例(Python 2.7). (注意:在我的实际用例中,MyClass是一个在我正在测试的某些代码中间接实例化的类):from mock import patchclass MyClass(object):def __init__(self):self.prop = 'prop'def foo(self):return 'foo'def bar(self):return 'bar'def unmocked(self):return '...