在Python中,如何在类实例的数据属性中自动设置类的名称?

2024-09-30 18:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在类实例的数据属性中自动设置类的名称?你知道吗

下面是一些示例代码:

def workFunctionTest(**kwargs):
time.sleep(3)
return kwargs

def printHR(object):
    # dictionary
    if isinstance(object, dict):
        for key, value in sorted(object.items()):
            print u'{0}: {1}'.format(key, value)
    # list or tuple
    elif isinstance(object, list) or isinstance(object, tuple):
        for element in object:
            print element
    # other
    else:
        print object

class Job(object):
    def __init__(
        self,
        workFunction=workFunctionTest,
        workFunctionArguments={'testString': "hello world"},
        naturalLanguageString=None
        ):
        self.workFunction=workFunction
        self.workFunctionArguments=workFunctionArguments,
        self.naturalLanguageString=naturalLanguageString
    def printout(self):
        """
        This method prints a dictionary of all data attributes.
        """
        printHR(vars(self))

def main():
    job1=Job(
        workFunction=workFunctionTest,
        workFunctionArguments={'testString': "hello world"},
    )
    print("Is the object an instance of the class?")
    print isinstance(job1, Job)
    print("a printout generated by a method of the object:")
    job1.printout()

if __name__ == '__main__':
    main()

如何将此代码打印输出的结尾改为:

naturalLanguageString: None
workFunction: <function workFunctionTest at 0x7f435461ac80>
workFunctionArguments: ({'testString': 'hello world'},)

对这个?地址:

naturalLanguageString: Job
workFunction: <function workFunctionTest at 0x7f435461ac80>
workFunctionArguments: ({'testString': 'hello world'},)

Tags: ofselfhelloworldobjectdefjobisinstance
3条回答

您可以这样做:

self.naturalLanguageString = self.__class__.__name__

作为额外的,您可以通过self.__class__访问所有类

self.naturalLanguageString = naturalLanguageString or self.__class__.__name__

这应该管用

如果不传递naturalLanguageString,则默认情况下将使用类名设置它

我想你在找self.__class__.__name__。你知道吗

相关问题 更多 >