[英]Python Troubles (Missing 1 required positional argument: 'self')
我正在尝试解决adventofcode谜语,但今年我决定借此机会学习一种新的编程语言:Python。由于我已经对其他 OOP 语言(如 Java 和 C++)有所了解,我立即创建了一个“接口”解决方案对象的系统。
我现在的项目设置是这样的:
现在我想要的是通过主要 class 动态 output 解决方案,基本上必须调用 /solutions/ 目录中每个 dayX.py class 的 all.solve() 方法。
我想我接下来要做,但我收到一个错误:
Traceback (most recent call last):
File "C:\Users\siste\j-workspace\adventofcode2020\main.py", line 16, in <module>
print(solution.solve())
TypeError: solve() missing 1 required positional argument: 'self'
这是我的文件:
主程序
import os
def days():
classes = []
path = "C:\\path"
for file in os.listdir(path):
if(file.startswith("day")) :
classes.append(str(file.replace(".py", "")))
return classes
if __name__ == '__main__':
for day in days() :
solution = getattr(__import__(str("solutions." + day)), day.replace("d", "D"))
print(solution.solve())
解决方案.py
path = "C:\\path\\inputs\\day{}.txt"
class Solution:
def __init__(self, dayNumber):
self.dayNumber = dayNumber
self.inputPath = path.format(self.dayNumber)
def part1(self):
pass
def part2(self):
pass
def solve(self):
return ("Day {} Solutions: \n\tPart1: {}\n\tPart2: {}"
.format(self.dayNumber, self.part1(), self.part2()))
day1.py
import fileinput
from solutions.solution import Solution
class Day1(Solution):
def __init__(self):
super().__init__(1)
def part1(self):
return "sol"
def part2(self):
return "sol2"
当您在导入的模块上使用getattr
时,您将获得 class 定义。 方法只能在 class 个实例上调用,否则它们会抛出您看到的错误:
class A:
def a(self):
pass
A.a() // Will throw "TypeError: a() missing 1 required positional argument: 'self'"
A().a() // OK
以这种方式更改__main__
部分应该可以解决问题:
if __name__ == '__main__':
for day in days() :
day_class = getattr(__import__(str("solutions." + day)), day.replace("d", "D"))
day_instance = day_class()
print(day_instance.solve())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.