相关疑难解决方法(0)

如何访问对应于该属性名称的给定字符串的对象属性

如何设置/获取t给定的属性值x.

class Test:
   def __init__(self):
       self.attr1 = 1
       self.attr2 = 2

t = Test()
x = "attr1"
Run Code Online (Sandbox Code Playgroud)

python attributes object

121
推荐指数
2
解决办法
7万
查看次数

动态调用函数 - Python

我有一个功能列表......例如

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)

python

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

将属性名称传递给Python中的函数

如何将对象属性的名称传递给函数?例如,我尝试过:

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 attributes

3
推荐指数
2
解决办法
6224
查看次数

如何将字符串转换为属性?

我正在尝试制作一个非常简单的基于命令的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还是比较陌生的,如果真的很明显,请对不起。谢谢您,我们将为您提供帮助。

python python-3.x

3
推荐指数
1
解决办法
47
查看次数

如何使用 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)

python python-3.6

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

标签 统计

python ×5

attributes ×2

object ×1

python-3.6 ×1

python-3.x ×1