I am trying to improve my understanding of OOP in Python 2.7 (uses in my University courses). My goal is to print the outcome by using a child class. However, I keep getting the below error and do not know how to fix it and why it pops up.
Can anybody tell me how to fix this code and what I am doing wrong?
Error:
Traceback (most recent call last):
File "*******"", line 36, in <module>
print_grades = CreateReport(ReadFile)
TypeError: __init__() takes exactly 1 argument (2 given)
Code:
# Constants
input_file = 'grades1.in.txt'
class ReadFile():
def __init__(self):
self.text_file =''
def read_file(self, file):
self.text_file = open(file)
def data_to_list(self):
self.list_grades = []
for x in self.text_file:
output = x.strip("\n").split("\n")
temp_list = []
for y in output:
temp_list.append(y)
self.list_grades.append(temp_list)
return self.list_grades
class CreateReport(ReadFile):
def __init__(self):
# ReadFile.__init__(self)
pass
def print_list(self):
data = ReadFile.data_to_list()
print data
# start_program(input_file)
print_grades = CreateReport(ReadFile)
print_grades.print_list()
Related
Traceback (most recent call last):
File "C:\Users\RAC\crypto\...\blockchain.py", line 178, in <module>
blockchain = Blockchain()
^^^^^^^^^^^^
File "C:\Users\RAC\crypto\...\blockchain.py", line 49, in __init__
self.chain = [self.create_genesis_block(0)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Blockchain.create_genesis_block() takes 1 positional argument but 2 were given
with code looking like this
class Blockchain:
def __init__(self):
self.chain = [self.create_genesis_block(0)]
self.difficulty = 4
self.nodes = dict()
self.replicated_nodes = dict()
self.coin_ledger = dict()
def create_genesis_block(self):
return Block("Genesis Block", "0", coin)
ive tried adding other arguments but as i am new to this, i havent been able to figure it out myself properly
def create_genesis_block(self): doesn't take a parameter, maybe you meant:
def create_genesis_block(self, block_num):
return Block("Genesis Block", block_num, coin)
or
#staticmethod
def create_genesis_block(block_num):
return Block("Genesis Block", block_num, coin)
when you use the self constructor, you need to initialize the class, try
instanse = Blockchain()
instanse.create_genesis_block()
i'm trying to solve the adventofcode riddles, but this year i decided to take the chance to learn a new programming language: Python.
Since i already have some knowledge about other OOP languages like Java and C++, i immediately created an "interface" system for the Solutions objects.
My project setup at the moment is like:
Project Setup
Now what i want is to dynamically output solutions through the main class, that basically has to call all .solve() method of each dayX.py class that is in the /solutions/ directory.
I think i'm next to do it but i get an error:
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'
Here are my files:
main.py
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())
solution.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"
When you're using the getattr on the imported module, you're getting the class definition. Methods are only callable on class instances, otherwise they throw the error you're seeing:
class A:
def a(self):
pass
A.a() // Will throw "TypeError: a() missing 1 required positional argument: 'self'"
A().a() // OK
Changing the __main__ part this way should solve the issue:
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())
I'm trying to pass variable list in Class and Function in object oriented manner but facing some error, I don't understand what wrong with it and I'm using PyDev in Eclipse
CODE
class Mydetails:
__details = ''
def __init__(self,details): # constructor
#self.__details['country'] = details['country']
self.__details = details
def set_element(self,details):
self.__details = details
def get_list(self,details):
return self.__details
details = ['ABC','DEF','GHI','JKL']
pdetails = Mydetails()
pdetails.set_element(details)
print(pdetails.get_list())
OUTPUT
Traceback (most recent call last):
File "C:\workspace\python\pythonapp\list.py", line 18, in <module>
pdetails = Mydetails()
TypeError: __init__() missing 1 required positional argument: 'details'
in this line:
def __init__(self,details):
you made the init function take a parameter (details), but here:
pdetails = Mydetails()
you arent giving it a parameter! what you probably wanted to do there is:
pdetails = Mydetails(details)
on a side note your def get_list(self,details): function doesn't make sense, why are you passing it a parameter that doesn't get used?
I fixed my code ,It was error in function def get_list(self,details): changed to def get_details(self): because details parameter already copied in self so it not allow the same thats why throwing error, but below code is fixed and work fine with function calling and defined object also correct from previous code.
CODE
class Mydetails:
__details = '' #protected
def __init__(self,details={}): # constructor
self.__details = details
def set_details(self,details): # function
self.__details = details
def get_details(self):
return self.__details
def toString(self):
return 'Welcome {}'.format(self.__details)
new_details = ['xyz','klm','nop']
pdetails = Mydetails()
pdetails.set_details(new_details)
print(pdetails.get_details())
OUTPUT
['xyz', 'klm', 'nop']
This is an exercise that I wanted to try because I thought it was interesting. The exercise is unnecessarily complex for what it is doing, but it is trying to act as practice for understanding class, function and variable behavior in more complex python programs.
import os
class grabFile:
fileObject = None
def __init__(self, filename):
self.fileObject = open(filename, "r")
def getFile():
return self.fileObject
class counter:
fileC = None
lineCount = 0
def __init__(self, fileObject):
self.fileC = fileObject
def lineCounter(self):
while True:
self.fileC.readline()
print(x)
return lineCount
def Main():
fileGrabber = grabFile("test.txt")
fileObj = fileGrabber.getFile
countObj = counter(fileObj)
lineCount = countObj.lineCounter()
print(lineCount)
Main()
However, when I run this, I get the following error:
Traceback (most recent call last):
File "/home/may/Desktop/Tree/Programming/MiscProjects/TextAnalyzer.py", line 32, in <module>
Main()
File "/home/may/Desktop/Tree/Programming/MiscProjects/TextAnalyzer.py", line 29, in Main
lineCount = countObj.lineCounter()
File "/home/may/Desktop/Tree/Programming/MiscProjects/TextAnalyzer.py", line 19, in lineCounter
self.fileC.readline()
AttributeError: 'function' object has no attribute 'readline'
[Finished in 0.2s with exit code 1]
Can anyone help me understand this program fully? And also, although this is not the correct place to ask, offer any critique on styling or formatting of the program? Especially one the use of "self".
Thank you!
I think you meant to call the method:
fileObj = fileGrabber.getFile()
And you need to change to instance method:
def getFile(self):
return self.fileObject
And your line counter method needs some work:
def lineCounter(self):
self.lineCount = len(self.fileC.readlines())
return self.lineCount
What is the error below? Also, is there a better way to implement the following classes?
#!/usr/bin/python
class Datacenters:
def __init__(self,name,location,cpu,mem):
self.name=name
self.location=location
self.cpu=cpu
self.mem=mem
def getparam(self):
return self.name,self.location ,self.cpu,self.mem
def getname(self):
return self.name
class WS(Datacenters):
def __init__(self,name,location,cpu,mem,obj):
#datacentername = Datacenters.__init__(self) #To which data center it is associated
self.dcname =obj.name #To which data center it is associated
Datacenters.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
self.name,self.location ,self.cpu,self.mem = obj.getparam()
print self.dcname
#return self.name,self.location ,self.cpu,self.mem,obj.name
def getwsname(self):
return self.name
class Pcs(WS):
def __init__(self,name,location,cpu,mem,obj):
self.wsname = obj.getwsname() #To which WS it is associated
WS.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
print obj.getparam()
print self.wsname
a = Datacenters("dc1","Bl1",20,30)
print a.getparam()
b = WS("WS1","Bl1",21,31,a)
print b.getparam(a)
c = Pcs("PC1","Bl1",20,30,b)
#print c.getparam(b)
output:
Press ENTER or type command to continue
('dc1', 'Bl1', 20, 30)
dc1
None
Traceback (most recent call last):
File "class1.py", line 45, in <module>
c = Pcs("PC1","Bl1",20,30,b)
File "class1.py", line 34, in __init__
WS.__init__(obj,name,location,cpu,mem)
TypeError: __init__() takes exactly 6 arguments (5 given)
The error is that you pass in five arguments, but the __init__ needs six. Count them:
def __init__(self,name,location,cpu,mem,obj):
Six arguments. You call it like so:
WS.__init__(obj,name,location,cpu,mem)
Five arguments. The first one, self is missing. What you should ask yourself is why you don't have to pass in six arguments all the time.
And that is because self is passed in automatically when you call the method on an instance. However, in this case you don't call it on an instance, you call it directly on the class. There is of course no need to do so in this case, the correct syntax is:
WS(obj,name,location,cpu,mem)
As you indeed above note works further up.