擅长:python、mysql、java
<p>因为您使用的是python3.6,所以您可以通过使用新的<a href="https://docs.python.org/3/reference/datamodel.html#object.__init_subclass__" rel="nofollow noreferrer">^{<cd1>}</a>方法来完成您的要求。来自<code>__init_subclass__</code>的文档:</p>
<blockquote>
<p>This method is called whenever the containing class is subclassed. cls is then the new subclass. If defined as a normal instance method, this method is implicitly converted to a class method.</p>
</blockquote>
<pre><code>class FirstClass:
def __init_subclass__(cls):
super().__init_subclass__()
if cls.property == "custom":
cls.name = "john"
else:
cls.name = "steve"
class SecondClass(FirstClass):
property = "custom"
print(SecondClass.name)
class SecondClass(FirstClass):
property = "notcustom"
print(SecondClass.name)
</code></pre>
<p>对于使用Python 3.5及更低版本的方法,可以使用一些元类魔术:</p>
^{pr2}$