所以我环顾四周,阅读了很多关于TypeError:message的帖子,其中“只提取X个参数,但只给出了1个”。
我知道self
。我不认为我有一个问题是self
。无论如何,我试图创建一个包含某些属性的类,只要我在函数@property
前面hwaddr
,就会出现以下错误:
Traceback (most recent call last):
File line 24, in <module>
db.hwaddr("aaa", "bbbb")
TypeError: hwaddr() takes exactly 3 arguments (1 given)
这是代码。为什么@property
搞砸了我?我把它拿出来,代码按预期工作:
#!/usr/bin/env python2.7
class Database:
"""An instance of our Mongo systems database"""
@classmethod
def __init__(self):
pass
@property
def hwaddr(self, host, interface):
results = [ host, interface ]
return results
db = Database()
print db.hwaddr("aaa", "bbbb"
Process finished with exit code 1
随着它的消失,输出是:
File
['aaa', 'bbbb']
Process finished with exit code 0
答案 0 :(得分:2)
属性用作语法糖吸气剂。因此,他们希望您仅通过self
。它基本上会缩短:
print db.hwaddr()
为:
print db.hwaddr
在此处传递两个参数时,无需使用属性。
答案 1 :(得分:1)
基本上,Dair说:属性不接受参数,这就是方法的用途。
通常,您需要在以下方案中使用属性:
所以问题是,hwaddr做了什么,它是否与这些用例相匹配?什么是主机和接口?我认为你想做的是:
<div class="b">
<div class="a" foo="bar">
<!-- various things here -->
</div>
</div>
此处,您的数据库类将具有主机和接口只读属性,这些属性只能在实例化类时设置。第三个属性 hwaddr 将生成一个包含数据库完整地址的元组,在某些情况下这可能很方便。
另请注意,我删除了 init 中的#!/usr/bin/env python2.7
class Database:
"""An instance of our Mongo systems database"""
def __init__(self, host, interface):
self._host = host
self._interface = interface
@property
def host(self):
return self._host
@property
def interface(self):
return self._interface
@property
def hwaddr(self):
return self._host, self._interface
db = Database("my_host", "my_interface")
print db.host
print db.interface
print db.hwaddr
装饰器;构造函数应该是实例方法。