【发布时间】:2014-07-04 10:01:18
【问题描述】:
我以前从未在 OOP 中编写过代码。我有一些函数来处理和验证增值税号码,我想将它们包含在一个类中(稍后,与处理 IBAN 帐号的其他类一起制作一个模块或一个包,我不确定两者有什么区别)。
我获取了一个增值税号(西班牙文为 CIF),首先,我需要将其从除数字和字母之外的任何其他字符中清除。然后验证号码。
输入:
h55/586-75 4
期望的输出:
H55586754
True
实际输出:
h55/586-75 4
False
我的代码:
import re
class CheckingCIF:
_letras = "ABCDEFGHIJKLMNPQRSVW" # Not used yet.
def __init__(self, un_cif):
self.cif = un_cif
self._limpiarCIF()
def _limpiarCIF(self):
self.cif = re.sub('\W', "", self.cif.upper())
return self
def validarCodigoCIF(self):
if len(self.cif) != 9:
return False
numero = self.cif[1:10]
pares = int(numero[1]) + int(numero[3]) + int(numero[5])
impares = 0
for i in range(0, 8, 2):
j = int(numero[i]) * 2
if j < 10:
impares += j
else:
impares += j - 9
digito = str(pares+impares)[-1]
if int(digito) == 0:
checkCIF = 0
else:
checkCIF = 10 - int(digito)
if str(checkCIF) == self.cif[-1]:
return True
else:
return False
if __name__ == "__main__":
entradaCodigoCIF = input('Enter the VAT number: ')
mi_cif = CheckingCIF(entradaCodigoCIF)
print(mi_cif.cif)
print(CheckingCIF.validarCodigoCIF(mi_cif))
问题不在于 validarCodigoCIF(self) 方法,因为我之前测试过,它工作正常。
问题可能出在 _limpiarCIF(self) 方法中,因为我不理解面向对象编程以及 self 字和静态方法的使用。
【问题讨论】:
标签: python oop static-methods self