Gre*_*ory 1 python methods class
我在使用Python的re模块创建类的实例时遇到了麻烦.这是我正在尝试做的事情:
我希望下面的代码片段能够在Record类re的terminal()方法中打印模块捕获的五个大写字母的字符串,但很明显我误解了一些东西.实际输出位于代码下方.
class SrcFile:
def __init__(self, which):
self.name = which
class Record(SrcFile):
def terminal(self):
recordline = re.compile(r"^([A-Z]{5})\s{3}")
if recordline.match(self):
m = recordline.match(self)
return m.group(1)
for f in files:
file = SrcFile(f)
for l in f:
record = Record(f)
print(record.terminal())
Run Code Online (Sandbox Code Playgroud)
同样,我希望每条记录行看到一个包含五个大写字母的字符串,但实际上我得到的是:
Traceback (most recent call last):
File "./next.py", line 78, in <module>
print(record.terminal())
File "./next.py", line 63, in terminal
if recordline.match(self):
TypeError: expected string or buffer
Run Code Online (Sandbox Code Playgroud)
如果有人能够在代码中解释原因,那也会很有帮助
for f in files:
file = SrcFile(f)
for l in f:
record = Record(f)
Run Code Online (Sandbox Code Playgroud)
使用它显然是不正确的record = Record(file).我通过反复试验发现了这一点,因为我无法使用带有错误代码的record.method()访问文件的SrcFile类的方法,但我不明白为什么.
我确信我在编程方面缺乏经验,特别是Python的经验非常明显.在此先感谢您的帮助.
你的意思是写
if recordline.match(self.name):
Run Code Online (Sandbox Code Playgroud)
而不是
if recordline.match(self):
Run Code Online (Sandbox Code Playgroud)
当你打电话时re.match,你应该用一个字符串这样做.self不是字符串,而是Record对象,而是self.name行中设置的字符串
self.name = which
Run Code Online (Sandbox Code Playgroud)
还有两个与您的其他问题相关的基本问题.
你永远不会使用这条线本身,l这就是你在文件中迭代的全部原因.也许你打算写Record(l).
为什么Record类继承SourceFile对象(带代码class Record(SourceFile)?)你应该仔细阅读有关继承的内容:继承用于在多个对象之间共享方法和属性,它并不真正适用于此代码.