Python 如何通过变量获取对象实例
假设我将Python 如何通过变量获取对象实例,python,Python,假设我将self.f发送到一个全局方法 def write_to_report(file_hdlr, content): 如果我想得到文件\u hdlr所属的对象 如何得到它?因为我需要知道文件属于哪一类, 并使用类名执行某些操作 def write_to_report(file_hdlr, content): file_hdlr.__self__ # ??? NO 代码 如果您想知道文件\u hdlr变量的类型,可以使用函数type: file_hdlr_type = type(f
self.f
发送到一个全局方法
def write_to_report(file_hdlr, content):
如果我想得到文件\u hdlr
所属的对象
如何得到它?因为我需要知道文件属于哪一类,
并使用类名执行某些操作
def write_to_report(file_hdlr, content):
file_hdlr.__self__ # ??? NO
代码
如果您想知道
文件\u hdlr
变量的类型,可以使用函数type
:
file_hdlr_type = type(file_hdlr)
你不能
另一种方法:
class ReportWriterMixin(object):
def write_to_report(self):
this_class = self.__class__
# do thing with self.f based on this_class
class CPUInfo(threading.Thread, ReportWriterMixin):
def __init__(self, config):
self.f = get_export_file_hdlr(self.__class__.__name__)
self.write_to_report()
这样,虽然您的方法不再是“全局”的,但它可以用于任何您喜欢的类。对象没有指向其“父对象”的隐式指针。如果你仔细想想,“父对象”的概念根本没有意义,因为当传递引用时,引用的副本就会被复制,而这个副本与原始引用一样有效。现在,您的对象属于两个不同的对象。他正在询问如何获取包含
文件\u hdlr
的原始self
引用…抱歉,我不明白
class ReportWriterMixin(object):
def write_to_report(self):
this_class = self.__class__
# do thing with self.f based on this_class
class CPUInfo(threading.Thread, ReportWriterMixin):
def __init__(self, config):
self.f = get_export_file_hdlr(self.__class__.__name__)
self.write_to_report()