擅长:python、mysql、java
<p>我猜<code>gen0</code>是这样定义的:</p>
<pre><code>class gen0:
pass
</code></pre>
<p>而不是在对象创建时初始化类中的属性</p>
<pre><code>class gen0:
def __init__(self):
# this function will be run when you call "g = gen0()"
# in the main body of you code. and the following properties
# will be set on object "g"
self.juvenile_population = 0
self.juv.... etc
</code></pre>
<p>所以我猜,当你试图在设置前访问类似<code>juvenile_population</code>的内容时,你得到的是<code>AttributeError</code>。</p>
<p>正确初始化类是进行面向对象编程的最佳方法。</p>
<p>然而,你的问题的字面答案是:</p>
<pre><code> g = gen0()
if "juvenile_population" in dir(g):
.... etc
</code></pre>
<p>请注意,这只检查对象是否具有<code>juvenile_population</code>属性,您需要更多的这些语句来检查每个属性,类似地,您可以在<a href="http://#%20this%20function%20will%20be%20run%20when%20you%20call" rel="nofollow" title="g = gen0()quot; # and the following properties will be set on object quot;g">Douglas' answer</a>中使用EAFP方法,但同样地,这将使用<code>try</code>语句大量地扩展您的代码。</p>