How would i fix this error in creating a genesis block - python

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()

Related

Inheritance in classes does not work in Python 2.7

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()

Understanding variable scopes in python: An Exercise Program

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

Subclassing builtin types -- Python 2 and 3

I have code that looks like the following:
class Token(object):
'''
Resulting from parse
'''
def __new__(cls,text,begin,end,*args,**kargs):
self = super(Token,cls).__new__(cls,*args,**kargs)
return self
def __init__(self,text,begin,end,*args,**kargs):
super(Token,self).__init__(*args,**kargs)
self.text = text
self.begin = begin
self.end = end
class List(Token,list):
pass
class Str(Token,str):
pass
class Int(Token,int):
pass
s = Str('hey there',0,3,'hey there'[0:3])
print(s)
x = Int('55 12',0,2,'55 12'[0:2])
print(x)
Basically what I want to do is to easily create types that are just normal Python types, but with some extra information to them.
Python 2 seems to be OK with the above code, but Python 3 complains
Traceback (most recent call last):
File "simple.py", line 71, in <module>
s = Str('',1,2,'hey')
File "simple.py", line 12, in __init__
super(Token,self).__init__(*args,**kargs)
TypeError: object.__init__() takes no parameters
I think the interpreters would be happy if I did something like
class List(list):
def __init__(self,text,begin,end,*args,**kargs):
list.__init__(*args,**kargs)
But this would mean I would have to repeat something similar for every new class I want to make... and I would rather stay relatively DRY...
Is there a 'proper' way I should handle this situation so that both Python 2 and Python 3 are happy?
Your best bet is to use exception handling here:
def __init__(self,text,begin,end,*args,**kargs):
try:
super(Token,self).__init__(*args,**kargs)
except TypeError:
# Python 3 and the mixed in type is immutable.
# Ignoring this is fine, `__new__` took care of this.
pass
self.text = text
self.begin = begin
self.end = end

Python Issue - Map and Classes - Beginner

I'm attempting to use Map to reference a class function, but am having difficulty with formatting/ordering. I have heard that using map is sort of obsolete so I am definitely open to alternative solutions (for loops?) Thanks in advance.
lognames = [ "C:\Users\makker1\Desktop\logs\loga.txt",
"C:\Users\makker1\Desktop\logs\logb.txt",
"C:\Users\makker1\Desktop\logs\logc.txt" ]
class LogFile:
def __init__(self,filepath):
self.logfile = open(filepath, "r")
self.head = None
def __str__(self):
return "x=" + str(self.x) + "y="+str(self.y)
def readline (self):
if self.head != None:
self.head = self.logfile.readline()
def previewline (self):
if self.head == None:
self.head = self.logfile.readline()
def close (self):
self.logfile.close()
logs = map(LogFile(self,filepath).__init__(), lognames)
heads = map(lambda log: None, logs)
>>>
Traceback (most recent call last):
File "C:\Users\makker1\Desktop\mergesort-final.py", line 30, in <module>
logs = map(LogFile(self,filepath).__init__, lognames)
NameError: name 'self' is not defined
>>>
If any more info is needed, please let me know. I realize that there are tons of posts about this very problem and have sorted through many of them with no avail.
Here is a list comprehension answer. I like this better than map().
logs = [LogFile(fname) for fname in lognames]
You don't have to call __init__ explicitly. Try:
logs = map(LogFile, lognames)
Sometimes it helps to think of a class as being callable. You can think of a class as something like the following:
def LogFile(filepath):
class _LogFile:
def __init__(self, path):
...
return _LogFile(filepath)
Basically, a class can be thought of as something that you call to create an object instance. This isn't really true, but in many cases it will appear to be.

not enough arguments passed to __init__()

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.

Categories