如何在类实例的数据属性中自动设置类的名称?你知道吗
下面是一些示例代码:
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'},)
您可以这样做:
作为额外的,您可以通过
self.__class__
访问所有类这应该管用
如果不传递naturalLanguageString,则默认情况下将使用类名设置它
我想你在找
self.__class__.__name__
。你知道吗相关问题 更多 >
编程相关推荐