社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中将属性名检索为字符串

Snykeurs • 3 年前 • 1163 次点击  

我想在python中检索属性名来创建类似指针的东西,现在我使用以下语句,但我并不满意:

class foo:
   name: str
   last_name: str

class other:
   def __init__(self, obj, var):
        obj.__dict__[var] = "John"
        

f = foo("Jon", "Jon")
o = other(f, "name")

我想写作

o = other(f, f.name)

或者更好

o = other(f.name)

我尝试了一些函数来检索名称,但它只适用于对象,而不适用于对象的属性:

def retrieve_name(var: object) -> str:
    for objname, oid in globals().items():
        if oid is var:
            return objname
        if hasattr(oid, "__dict__"):
            for child in oid.__dict__:
                # dont work because id is the same if value is the same
                if id(oid.__dict__[child]) == id(var):
                    return child

只有当我使用 retrieve_name(f) -> f 但如果我使用 retrieve_name(f.last_name) -> name 如果 f.name == f.last_name 因为 id(f.name) == id(f.last_name) 当字符串值相同时

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129322
 
1163 次点击  
文章 [ 1 ]  |  最新文章 3 年前
pppig
Reply   •   1 楼
pppig    3 年前

如果是绑定一个对象,这是否能简单快速地满足您的需求。

object.__setattr__

尝试属性分配时调用。它被调用,而不是正常的机制(即将值存储在实例字典中)。name是属性名,value是要分配给它的值。

class foo:
    name: str = ""
    last_name: str = ""


class other:
    def __init__(self, obj):
        self.__dict__["obj"] = obj

    def __setattr__(self, key, value):
        if not hasattr(self, key) and hasattr(self.__dict__["obj"], key):
            setattr(self.__dict__["obj"], key, value)
        else:
            super().__setattr__(key, value)


f = foo()
o = other(f)
print("1. ", f.name, f.last_name)
o.name = "Jon"
print("2. ", f.name, f.last_name)

"""
1.   
2.  Jon 
"""