<p>可以为类编写动态构造函数(<code>def __init__</code>),以便:</p>
<pre><code>class User(object):
__attrs = ['Policy', 'Level', 'StartDate', 'EndDate', 'StartTime',
'EndTime', 'Name', 'Mobile']
def __init__(self, **kwargs):
for attr in self.__attrs:
setattr(self, attr, kwargs.get(attr, None))
def __repr__(self):
return ', '.join(
['%s: %r' % (attr, getattr(self, attr)) for attr in self.__attrs])
</code></pre>
<ul>
<li>变量<code>__attrs</code>存储变量名。我使用了双下划线变量,因此无法从extend访问它。你知道吗</li>
</ul>
<pre><code>user = User()
print(user.__attrs)
Traceback (most recent call last):
print(user.__attrs)
AttributeError: 'User' object has no attribute '__attrs'
</code></pre>
<p><em>是的,有其他方法可以访问双下划线变量,但没有人会这样做;)</em></p>
<ul>
<li>如果函数<code>__str__</code>不存在,则函数<code>__repr__</code>通过调用<code>print</code>或<code>str</code>返回<code>string</code>。你知道吗</li>
</ul>
<p>你知道吗
现在测试一下</p>
<pre><code>>>> u1 = User(Name='user1')
>>> u2 = User(Name='user2', Policy=1, Level=3)
>>> print(u1)
Policy: None, Level: None, StartDate: None, EndDate: None, StartTime: None, EndTime: None, Name: 'user1', Mobile: None
>>> print(u2)
Policy: 1, Level: 3, StartDate: None, EndDate: None, StartTime: None, EndTime: None, Name: 'user2', Mobile: None
</code></pre>
<p>如果您使用我的代码,您可以打印案例中的项目,以便:</p>
<pre><code>for item in lstOnCall:
print item
</code></pre>
<p><strong>代码的其他问题</strong><br/>
Python中没有定义<code>Function overloading</code>。您可以在python中定义同名的多个函数。但这毫无意义。只有<strong>最后的<strong>定义仍保留在<code>class</code>/<code>module</code>中。前面的定义将被覆盖。你在做什么</p>
<pre><code>class User:
def __init__(self, a, b, c):
...
def __init__(self):
pass
</code></pre>
<p>是<strong>假<strong>。它在<strong>Java</strong>或<strong>C#</strong>中工作,但在<strong>Python</strong>中不工作。函数<code>def __init__(self, a, b, c)</code>将被覆盖。类中只存在函数<code>def __init__(self)</code>。你知道吗</p>