如何设置/获取t
给定的属性值x
.
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
t = Test()
x = "attr1"
Run Code Online (Sandbox Code Playgroud) 如何引用this_prize.left
或this_prize.right
使用变量?
from collections import namedtuple
import random
Prize = namedtuple("Prize", ["left", "right"])
this_prize = Prize("FirstPrize", "SecondPrize")
if random.random() > .5:
choice = "left"
else:
choice = "right"
# retrieve the value of "left" or "right" depending on the choice
print("You won", this_prize.choice)
AttributeError: 'Prize' object has no attribute 'choice'
Run Code Online (Sandbox Code Playgroud) 假设我创建了一个类的实例,并希望为其公共属性分配一些值.通常,这将是这样做的:
class MyClass:
def __init__(self):
self.name = None
self.text = None
myclass = MyClass()
myclass.name = 'My name'
Run Code Online (Sandbox Code Playgroud)
但是,如果编写一个将类作为参数的函数,并且我想动态地为该类的公共属性分配一些值 - 即通过变量和循环(不知道它们有多少或它们被调用). )
显而易见的是:
myclass = MyClass()
myclass['name'] = "My name"
Run Code Online (Sandbox Code Playgroud)
但这不起作用.
有任何想法吗?