我有一个对象列表,我想比较一个字符串(实际上是int,但我可以将其强制转换为str),以检查列表中的任何对象都将该字符串作为成员。
现在有一种方法可以遍历所有对象,并将val1
成员与我的字符串进行比较,但是我想知道是否可以执行以下方法?
class Check:
def __init__(self, val1):
self.val1 = val1
def __str__(self):
return str(self.val1)
o1 = [Check(100)]
test = "100"
for x in o1:
print(x)
print(test in o1)
但print(test in o1)
返回false
答案 0 :(得分:2)
仅仅因为您的方法返回的字符串表示形式等于其他对象的字符串表示形式,并不会使这些对象比较相等。
如果您希望将类的实例与具有相同字符串表示形式的其他对象等同对待,则可以添加实现该功能的__eq__
方法:
def __eq__(self, other):
return str(self) == str(other)
然后您会在测试案例中发现test in o1
评估True
。
请注意,如果执行此操作,那么Check(100) == Check('100')
也会评估True
(即使它们的val1
属性具有不同的类型)。您没有具体说出是否要这样做,但是您希望Check(100) == '100'
评估True
的事实强烈表明了这种情况。
答案 1 :(得分:2)
如果__eq__
参数是字符串,则可以覆盖other
运算符,也可以与另一个Check
对象进行比较
def __eq__(self, other):
if isinstance(other, str):
return other == str(self.val1)
if isinstance(other, Check):
return other.val1 == self.val1
答案 2 :(得分:0)
使用typing
的完整示例。
from typing import List
class Check:
def __init__(self, val1: str or int):
self.val1 = val1
def __str__(self):
return str(self.val1)
def __eq__(self, other):
comparison_type = str
if not isinstance(self.val1, comparison_type):
self.val1 = comparison_type(self.val1)
if not isinstance(other, comparison_type):
other = comparison_type(other)
return self.val1 == other
if __name__ == "__main__":
o1: List[Check] = [Check(100)]
test: str = "100"
print(test in o1)
答案 3 :(得分:0)
O1由实例列表组成,因为您实例化了Check类,并且正在将其与字符串进行比较,这当然是行不通的。 Test是一个字符串对象,而o1包含的一个对象则是一个Check对象(如果在上面运行,则type()将返回该对象)。
请注意,__str__
与将对象转换为字符串无关:它仅用于“漂亮打印”(例如,通过打印功能完成),并且在运行时被print()
调用给定对象上的内容,与__repr__
形成对比,相反,__eq__
的意思是提供更多原始的,技术的,与实现相关的显示。
为了支持对象并准确定义对象在这种情况下的行为,需要重载其他东西:即__ne__
和<template>
<v-container fluid>
<v-row align="center">
<v-col cols="12" sm="6">
<v-select
v-model="selected"
:items="projects"
:menu-props="{ maxHeight: '400' }"
label="Select"
hint="Pick Project"
persistent-hint
@change="getTickets()"
></v-select>
</v-col>
<v-col cols="12">
<v-card>
<v-card-title>
Tickets
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
show-select
item-key="name"
></v-text-field>
</v-card-title>
<v-simple-table>
<template v-slot:default>
<thead>
<tr>
<th class="text-left">ID</th>
<th class="text-left">Subject</th>
<th class="text-left">Priority</th>
<th class="text-left">Requester</th>
<th class="text-left">Type</th>
<th class="text-left">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="item in desserts" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.subject}}</td>
<td>{{ getPriority (item.priority) }}</td>
<td>{{ item.requester_id }}</td>
<td>{{ getType(item.type_id)}}</td>
<td>
<div class="my-2">
<v-btn small >Component Call</v-btn>
</div>
</td>
</tr>
</tbody>
</template>
</v-simple-table>
<v-pagination
v-model="pagination.current"
:length="pagination.total"
@input="onPageChange"
></v-pagination>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
import Vue from "vue";
import axios from "axios";
import { api } from "../../config";
import AxiosPlugin from "vue-axios-cors";
Vue.use(AxiosPlugin);
export default {
data() {
return {
selected: [],
e7: [],
projects: [],
loadingprop: true,
selecteddatatable: [],
search: "",
headers: [
{ text: "ID", value: "id" },
{ text: "Model", value: "model" },
{ text: "Priority", value: "priority" },
{ text: "Requester", value: "requester_id" },
{ text: "Status", value: "status" },
{ text: "Subject", value: "subject" },
{ text: "Type", value: "type_id" },
],
desserts: null,
pagination: {
current: 1,
total: 0,
},
};
}
</script>
。