如何设置/获取t给定的属性值x.
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
t = Test()
x = "attr1"
Run Code Online (Sandbox Code Playgroud) 我有一个功能列表......例如
def filter_bunnies(pets): ...
def filter_turtles(pets): ...
def filter_narwhals(pets): ...
Run Code Online (Sandbox Code Playgroud)
有没有办法通过使用表示其名称的字符串来调用这些函数?
例如
'filter_bunnies', 'filter_turtles', 'filter_narwhals'
Run Code Online (Sandbox Code Playgroud) 如何将对象属性的名称传递给函数?例如,我尝试过:
def foo(object, attribute):
output = str(object.attribute)
print(output)
class Fruit:
def __init__(self, color):
self.color = color
apple = Fruit("red")
foo(apple, color)
Run Code Online (Sandbox Code Playgroud)
但上述方法不起作用,因为Python认为,在中foo(apple, color),color指的是一个单一化的变量.
我正在尝试制作一个非常简单的基于命令的python脚本,并从终端的输入获取命令,但是它没有检测到变量的值...我不善于解释,所以这是我的代码:
a = 0
b = 0
class commands:
def add():
a = int(input("first number "))
b = int(input("second number "))
print(a + b)
commander = commands
cmd = input("what command ")
commander.cmd()
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它给我一个错误,提示Exception has occurred: AttributeError
type object 'commands' has no attribute 'cmd'
我对Python还是比较陌生的,如果真的很明显,请对不起。谢谢您,我们将为您提供帮助。
我使用 json 数据创建了一个命名空间,如下所示,从这个SO 答案中学到
>>> from __future__ import print_function
>>> import json
>>> from types import SimpleNamespace as Namespace
>>> data = '{"name": "John Smith", "hometown": {"name": "New York", "id": 123}}'
>>> x = json.loads(data, object_hook=lambda d: Namespace(**d))
>>> x.name
'John Smith'
Run Code Online (Sandbox Code Playgroud)
但是如果“名称”来自一个变量,我该如何访问它?
>>> foo='name'
>>> x.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'types.SimpleNamespace' object has no attribute 'foo'
>>>
Run Code Online (Sandbox Code Playgroud)