是否有可能做这样的事情:class ParentClassName(object): name = camel_case_to_underscore(cls.__name__)class ChildClassName(Parent): passassert Parent().name == "parent_class_name" assert Child().name == "child_class_name" assert Child.name == "child_class_name" assert getattr(Child, 'name') == "child_class_name" 我想创建一个类,其他类可以从中继承并根据类名设置其名称。在python 3中可能吗?
2 回答
饮歌长啸
TA贡献1951条经验 获得超3个赞
你不需要它,它已经在那里了:
>>> class Parent(): pass
...
>>> class Child(): pass
...
>>> Parent.__name__
'Parent'
>>> Child.__name__
'Child'
>>>
但是,如果您真的出于不费心解释的任何原因坚持自己滚动,则可以使用自定义元类:
def camel_case_to_underscore(name):
# your code here
class NamedType(type):
def __new__(meta, name, bases, attribs):
attribs["name"] = camel_case_to_underscore(name)
return type.__new__(meta, name, bases, attribs)
class Parent(metaclass=NamedType):
pass
class Child(Parent):
pass
添加回答
举报
0/150
提交
取消