如何将类类型名称更改为classobj以外的其他名称?
class bob():
pass
foo = bob
print "%s" % type(foo).__name__
Run Code Online (Sandbox Code Playgroud)
这让我'classobj'.
Jar*_*die 14
在您的示例中,您已定义foo为对类定义的引用bob,而不是bob实例的引用.确实是(旧式)类的类型classobj.
bob另一方面,如果实例化,结果将会有所不同:
# example using new-style classes, which are recommended over old-style
class bob(object):
pass
foo = bob()
print type(foo).__name__
'bob'
Run Code Online (Sandbox Code Playgroud)
如果您只是想在bob不实例化的情况下查看类型的名称,请使用:
print bob.__name__
'bob'
Run Code Online (Sandbox Code Playgroud)
这是因为bob它已经是类类型,因此具有__name__可以查询的属性.
Ale*_*lli 11
class DifferentTypeName(type): pass
class bob:
__metaclass__ = DifferentTypeName
foo = bob
print "%s" % type(foo).__name__
Run Code Online (Sandbox Code Playgroud)
DifferentTypeName根据您的需要发出.这似乎不太可能实际上是你想要的(或需要的),但是,嘿,这是你明确要求的方式:改变一个类的type名字.type为... foo.__class__或bob.__class__更高版本分配合适的重命名派生词也可以使用,因此您可以将其封装到一个非常奇特的函数中:
def changeClassTypeName(theclass, thename):
theclass.__class__ = type(thename, (type,), {})
changeClassTypeName(bob, 'whatEver')
foo = bob
print "%s" % type(foo).__name__
Run Code Online (Sandbox Code Playgroud)
这会发出whatEver.