python-3.x 如何获取对象属性的名称?[关闭]

a64a0gku  于 8个月前  发布在  Python
关注(0)|答案(1)|浏览(74)

已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

9天前关闭
Improve this question
我正在写我的第一个python程序
我创建了一个类,声明了属性
如何获取属性'x'或'y'的名称并将其分配给变量'name_property'以实现函数'operation'?
您将无法按属性的值进行搜索,因为x,y可以相等

class MyClass:
    def __init__(self, x, y):
        self.__x = x
        self.__y = y

    @property
    def x(self):
        return self.__x

    @property
    def y(self):
        return self.__y

    def operation(value):

        name_value = '???'

        if name_value == 'x':
            return value + 1

        elif name_value == 'y':
            return value - 1

    operation(MyClass.x)
    operation(MyClass.y)

字符串

kb5ga3dv

kb5ga3dv1#

要在Python中获取对象属性的名称,可以使用getattr()函数。getattr()函数返回对象的命名属性的值。因此,在您的示例中:

class MyClass:
    def __init__(self, x, y):
        self.__x = x
        self.__y = y

    @property
    def x(self):
        return self.__x

    @property
    def y(self):
        return self.__y

def operation(value):
    if value == getattr(obj, "x"):
        return value + 1

    elif value == getattr(obj, "y"):
        return value - 1

    else:
        # handle case when value is not found
        return None

# Create an instance of MyClass
obj = MyClass(10, 20)

# Call the operation function, passing in the value to search for
result1 = operation(obj.x)
result2 = operation(obj.y)

print(result1, result2)  # Expected output: 11 19

字符串

相关问题