简体   繁体   English

如何检查Python csv.writer实例的类?

[英]How do you check the class of a Python csv.writer instance?

I have a function that will write a python list to various formats. 我有一个功能,可以将python列表写成各种格式。 csv is one of the formats I would like to write out to. csv是我要写的格式之一。 I know i use the built-in csv Python module, but my function is currently written in the following manner: 我知道我使用内置的csv Python模块,但是我的函数当前是以以下方式编写的:

def foo(self, save_to=None):
    if save_to is None:
        print self.my_list

I can check the type of the csv.writer object by doing: 我可以通过执行以下操作来检查csv.writer对象的类型:

writer = csv.writer(open('test.csv','w'))
writer
<_csv.writer at 0x7f278125aca8>    

type(writer)
_csv.writer

How do I check to see in my function if save_to is an csv object? 我如何检查是否在save_to是一个csv对象在我的功能? Usually I'd use the isinstance in a function function like such: 通常我会在函数函数中使用isinstance ,例如:

def foo(self, save_to=None):
    if save_to is None:
        print self.my_list
    if isinstance(save_to, _csv.writer):
        save_to.writerow([self.my_list])

but I'm getting a NameError and AttrubuteError 但我收到一个NameErrorAttrubuteError

In [28]: isinstance(writer, _csv.writer)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-0af1f54bd092> in <module>()
----> 1 isinstance(writer, _csv.writer)    

NameError: name '_csv' is not defined    

In [29]: isinstance(writer, csv._csv.writer)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-29-4e8e62254caf> in <module>()
----> 1 isinstance(writer, csv._csv.writer)    

AttributeError: 'module' object has no attribute '_csv

You shouldn't use an isinstance check here (and especially not with a class in a private module like _csv ): isinstance calls violate OOP in general. 您不应该在这里使用isinstance检查(尤其是不要与_csv这样的私有模块中的类_csv ): isinstance调用通常会违反OOP。 More specific to Python, its "duck-typing" means that you should just try and use the method and catch attribute errors: if it quacks like a duck, it's a duck -- if it implements writerow like a csv writer, it's a csv writer. 更具体地讲,Python的“鸭式输入”意味着您应该尝试使用方法并捕获属性错误:如果它像鸭子一样writerow ,那就是鸭子-如果它像csv writerow一样实现writerow ,那就是csv作家。

try:
    save_to.writerow([self.my_list])
except AttributeError:
    # not a csv writer, do something else

More specifically though, the reason you're getting the errors you detail is because the submodule isn't imported. 但是,更具体地说,出现详细错误的原因是因为未导入子模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM