Python面向对象实现成员检测运算符in

文章目录

  • 问题描述
  • 解决方案
  • 参考文献

问题描述

stocks.csv

"Symbol","Price","Date","Time","Change","Volume"
"AA","39.48","6/11/2007","9:36am","-0.18","181800"
"AIG","71.38","6/11/2007","9:36am","-0.15","195500"
"AXP","62.58","6/11/2007","9:36am","-0.46","935000"
"BA","98.31","6/11/2007","9:36am","+0.12","104800"
"C","53.08","6/11/2007","9:36am","-0.25","360900"
"CAT","78.29","6/11/2007","9:36am","-0.23","225400"




解决方案

实现 __contains__(self, item) 方法

import csv


class Filter:
    def __init__(self):
        with open('stocks.csv') as f:
            f = csv.DictReader(f)
            self.data = [i for i in f]
            self.Symbol = [i['Symbol'] for i in self.data]

    def __contains__(self, item):
        return item in self.Symbol


if __name__ == '__main__':
    filter = Filter()
    print('AA' in filter)
    print('BB' in filter)
    # True
    # False




参考文献

  1. 数据模型 — Python 文档
  2. Python读取CSV文件使用csv库而不是直接读取
  3. Python中Class里的__contains__(self,x)函数解析

你可能感兴趣的:(Python,python,csv,filter)