是否可以在python中从字典创建一个对象,使每个键都是该对象的属性?
像这样的东西:
d = { 'name': 'Oscar', 'lastName': 'Reyes', 'age':32 }
e = Employee(d)
print e.name # Oscar
print e.age + 10 # 42
Run Code Online (Sandbox Code Playgroud)
我认为这几乎与这个问题相反:来自对象字段的Python字典
所以,我在回答这个问题时正在玩Python ,我发现这是无效的:
o = object()
o.attr = 'hello'
Run Code Online (Sandbox Code Playgroud)
由于AttributeError: 'object' object has no attribute 'attr'.但是,对于从object继承的任何类,它是有效的:
class Sub(object):
pass
s = Sub()
s.attr = 'hello'
Run Code Online (Sandbox Code Playgroud)
打印s.attr按预期显示"你好".为什么会这样?Python语言规范中的内容指定您不能将属性分配给vanilla对象?
(用Python shell编写)
>>> o = object()
>>> o.test = 1
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
o.test = 1
AttributeError: 'object' object has no attribute 'test'
>>> class test1:
pass
>>> t = test1()
>>> t.test
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t.test
AttributeError: test1 instance has no attribute 'test'
>>> t.test = 1
>>> t.test
1
>>> class test2(object):
pass
>>> t = test2()
>>> t.test = 1
>>> …Run Code Online (Sandbox Code Playgroud) 在Javascript中它将是:
var newObject = { 'propertyName' : 'propertyValue' };
Run Code Online (Sandbox Code Playgroud)
怎么用Python做?
我有一个非常基本的问题.
假设我调用一个函数,例如,
def foo():
x = 'hello world'
Run Code Online (Sandbox Code Playgroud)
如何让函数以这样的方式返回x,我可以将它用作另一个函数的输入或者在程序体内使用变量?
当我使用return并在另一个函数中调用该变量时,我得到一个NameError.
在python中是否存在创建空对象的特殊类?我尝试了object(),但它不允许我添加字段.我想这样使用它:
obj = EmptyObject()
obj.foo = 'far'
obj.bar = 'boo'
Run Code Online (Sandbox Code Playgroud)
我应该每次(在几个独立的脚本中)定义这样的新类吗?
class EmptyObject:
pass
Run Code Online (Sandbox Code Playgroud)
我用python2.7
我正在搞乱继承的类,并想知道是否可以使用方法设置自定义对象属性.它会像这样工作:
class MyClass(object):
def __init__(self):
super.__init__()
def setCustAttr(self, name, value):
#...
g=MyClass()
g.setCustAttr("var",5)
g.var+=6
g.var="text"
Run Code Online (Sandbox Code Playgroud)
exec("self."+string+"="+value)吗?我正在尝试创建一个动态函数,该函数动态添加属性以轻松地在 jinja 模板中访问值。
此代码正在运行,但它是静态的。
# Used to display a cart summary of items that have been pledged.
products_in_cart = Cart.query.filter(Cart.campaign_id == campaign_id).all()
# total_cart_quantity(products_in_cart, "quantity", "quantity_total")
for item in products_in_cart:
item.quantity_total = 0 #Adding the attribute quantity_total
for item_loop2 in products_in_cart:
if item.user_id == item_loop2.user_id:
item.quantity_total = item.quantity_total + item_loop2.quantity
# Remove duplicate objects based on user_id attribute.
new_set = set()
new_list = []
for obj in products_in_cart:
if obj.user_id not in new_set:
new_list.append(obj)
new_set.add(obj.user_id)
products_in_cart = new_list
Run Code Online (Sandbox Code Playgroud)
我想根据传递给函数的参数使添加的属性名称动态化,以便我可以在其他地方使用。点表示法不起作用,因为我需要一个变量来命名属性。obj[variable_atrbute] 错误。setattr() …
python ×8
attributes ×3
class ×1
dictionary ×1
flask ×1
function ×1
instances ×1
properties ×1
python-2.7 ×1
python-3.x ×1