全部 我有一个关于 python 中的类实例化的问题。 所以我有一堆不同类型的数据存储在同一个目录中,我只想使用仅适合该类型的 python 类来处理其中一种类型。不幸的是,数据的类型只有在通过类读入时才知道。 所以我想知道如果数据类型不正确,是否有一种方法可以简单地停止
__init__()
中的类实例化,并在读取所有数据时简单地传递到下一个数据集?
或者在类实例化时进行验证是一个坏主意?
非常感谢!
正确的方法是,如果提供给类的数据类型错误,则引发错误:
class MyClass(object):
def __init__(self, data):
if not isinstance(data, correct_type):
raise TypeError("data argument must be of type X")
然后用 try except 子句包装你的实例化:
try:
myInstance = MyClass(questionable_data)
except TypeError:
#data is not the correct type. "pass" or handle in an alternative way.
这是有利的,因为它使得数据需要是某种类型的事实变得显而易见。
另一种选择是按照 sberry 所说的那样,并在尝试实例化类之前显式测试数据类型:
if isinstance(data, correct_type):
myInstance = MyClass(data)
else:
#data is not the correct type. "pass" or handle in an alternative way.
class MyClass(object):
def __init__(self,data):
if type(data) is int: #In this example we don't want an int, we want anything else
pass
else:
#do stuff here
然后像这样使用它:
MyClass('This is ok')
或
MyClass(92) #This is not ok
def __init__()
处进行验证可以使用点符号来传递