如何检查类是否具有`' attr'的属性在实例`语法中
我希望能够在实例语法中使用'attr'来检查我的dataclass是否具有指定的属性,但我似乎无法使其正常工作。
我想要的是与熊猫的示例相同的行为
import pandas as pd
df = pd.DataFrame(columns=['a', 'b', 'c'])
print('a' in df)
True
,但仅适用于自定义数据级
from dataclasses import dataclass
@dataclass
class User:
email: int
password: str
blocked_at: float = None
def __getitem__(self, item):
return getattr(self, item)
user = User('[email protected]', 'password')
print(user['email'])
'email' in user
[email protected]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [35], in <cell line: 1>()
----> 1 'email' in user in User.__getitem__(self, item)
7 def __getitem__(self, item):
----> 8 return getattr(self, item)
TypeError: getattr(): attribute name must be string
I want to be able to use the 'attr' in instance
syntax to check if my dataclass has the specified attribute but I can't seem to make it work.
What I want is same behavior as this example with pandas
import pandas as pd
df = pd.DataFrame(columns=['a', 'b', 'c'])
print('a' in df)
True
But just for a custom dataclass
from dataclasses import dataclass
@dataclass
class User:
email: int
password: str
blocked_at: float = None
def __getitem__(self, item):
return getattr(self, item)
user = User('[email protected]', 'password')
print(user['email'])
'email' in user
[email protected]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [35], in <cell line: 1>()
----> 1 'email' in user in User.__getitem__(self, item)
7 def __getitem__(self, item):
----> 8 return getattr(self, item)
TypeError: getattr(): attribute name must be string
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生的事情是您没有定义正确的钩子。您要实现
_________________________________ a>。
因为您没有,所以操作员中的
切换到后备模式:通过对象迭代,就好像它是序列,所以它尝试
对象[1] 等。直到它击中object [0]
,然后indexError
或找到等于您要测试的值的东西。因此,例外,因为item
是0
。使用
HASATTR
而不是getAttr
,因为您想要 boolean 结果。对于您的__ getItem __
,您要确保将attributeError
exceptions tokeyError
异常旋转,以保持接口一致:demo:demo:
请参阅<<<<<<<<< a href =“ https://docs.python.org/3/reference/expressions.html#membership-test-details” rel =“ nofollow noreferrer”> python Referitiations on in is会员测试操作 中的
如何回到迭代:
What is happening is that you didn't define the correct hook. You want to implement the
__contains__
method.Because you didn't, the
in
operator switches to the fallback mode: iterating over the object as if it was a sequence, so it triesobject[0]
,thenobject[1]
, etc. until it hits anIndexError
or finds something that is equal to the value you were testing for. Hence, the exception, asitem
is0
.Use
hasattr
instead ofgetattr
, as you want a boolean result. And for your__getitem__
, you want to make sure you turnAttributeError
exceptions intoKeyError
exceptions, to keep the interface consistent:Demo:
See the Python reference section on membership test operations for the details on how
in
will fall back to iteration: