Error in function in class - takes exactly 1 argument - python

I have a class where I pass a list of documents, and in a method, it creates a list of those documents:
class Copy(object):
def __init__(self, files_to_copy):
self.files_to_copy = files_to_copy
Here, it creates a list of files:
def create_list_of_files(self):
mylist = []
with open(self.files_to_copy) as stream:
for line in stream:
mylist.append(line.strip())
return mylist
Now, I try to access the method in another method in the class:
def copy_files(self):
t = create_list_of_files()
for i in t:
print i
Then I run the following under if __name__ == "__main__":
a = Copy()
a.copy_files()
This throws:
TypeError: create_list_of_files() takes exactly 1 argument (0 given)
Am I using the method wrong?

You need to call the method off self, which is the "1 argument" the method is looking for
t = self.create_list_of_files()

You need to call create_list_of_files as follow:
self.create_list_of_files()

You are not passing any variable to the class. In your init method, your code states that init takes one variable, files_to_copy. You need to pass the variable that stores the correct information. For instance:
class Copy(object):
def __init__(self, files_to_copy):
self.files_to_copy = files_to_copy
#need to pass something like this:
a = Copy(the_specific_variable)
#now, can access the methods in the class

Related

TypeError: setSubregion_id() missing 1 required positional argument: 'subregion_id'

I'm trying to write a Build Pattern project. I'm not sure why I have this error:
TypeError: setSubregion_id() missing 1 required positional argument: 'subregion_id'
from enum import Enum, unique
#unique
class Subregions(Enum):
PL002 = 1
PL002 = 2
class InstanceBuilder(object):
def __init__(self):
self.subregion_id = Subregions()
def getSubregion_id(self):
return self.subregion_id
def setSubregion_id(self, subregion_id):
subregion_id = Subregions()
return subregion_id
class Instance():
def __init__(self, subregion_id ):
self.subregion_id = subregion_id
from Builder.InstanceBuilder import InstanceBuilder
from Builder.Subregions import Subregions
def main():
instance = InstanceBuilder.setSubregion_id(Subregions.PL001).build
if __name__ == "__main__":
main()
Code:
def main():
instanceBuilder = InstanceBuilder()
instance = instanceBuilder.setSubregion_id(Subregions.PL001).build
When you call InstanceBuilder.setSubregion_id, you using it as an unbound method, so it will not be able to access the attributes defined in the __init__ function, unless you already have a class object defined so you can pass it in as the self parameter.
But that wouldn't make sense, because if you already have the class object defined, you can simple do
class_object = InstanceBuilde()
class_object.setSubregion_id(Subregions.PL001).build`
instead of
class_object = InstanceBuilde()
InstanceBuilder.setSubregion_id(class_object, Subregions.PL001).build
So basically, because you are using the function as an unbound method, python takes the Subregions.PL001 you passed into the brackets as the self argument, hence it thinks that it's the subregion_id argument that's missing.
def main():
instance = InstanceBuilder.setSubregion_id(Subregions.PL001).build
to
def main():
instance = InstanceBuilder().setSubregion_id(Subregions.PL001).build
Read the differences between an unbound method and a bound method here:
Objects vs instance in python

adding item to a list within an instance of a class

I have a class with four lists. I intend to create several instances of this class. If I understand correctly, each instance should have its own lists. I wrote a function to add to the list, but I am struggling to make it work. I do need to use input ().with the following code I get the message: type error. line 12. add_item_list_one() missing one required positional argument : self
class My_class:
def __init__(self):
self.list_one = []
self.list_two = []
self.list_three = []
self.list_four = []
def add_item_list_one(self):
self.list_one.append(int(input()))
obj_one = My_class
obj_one.add_item_list_one()
You just assign My_class to obj_one, but do not instanciate it. Add parentheses after My_class to assign an instance of your My_class to obj_one:
obj_one = My_class()
obj_one.add_item_list_one()

Python Unbound method error?

I'm trying to inherit from this class:
class Event(Clock, Calendar):
def __init__(self):
year,month,day, hours, minutes,seconds = time.localtime()[0:6]
eClock = Clock(hours,minutes,0)
eCal = Calendar(month, day, year)
def createEvent(self,year,month,day,hours,minutes):
year,month,day = date[0:]
hours,minutes = ttime[0:2]
In order to create an event here:
sett = line[1:].split(",") # Line[1:] is going to be a
# date, such as 1/8/17 17:50.
date = sett[0]
ttime = sett[1]
ttime = ttime.split(":")
date = date.split("/")
Cevent = ttime + date
Cevent.event()
I have another class, called Reminder, that inits this:
event = Event.createEvent()
Anytime I try to run this program though, it gives me this error:
TypeError: unbound method createEvent() must be called with Event
instance as first argument (got nothing instead)
Im wondering why, and how I could take the method createEvent and use it in another class in the same file.
A bound method means that the method is called from a class. Let's look at an example:
class MyClass:
def add(self, x, y):
return x+y
vs
def add_numbers(x, y):
return x+y
The method add_numbers() is an unbound method, meaning it is not attached to any class instance. To use it, we can just call:
print(add_numbers(1, 2))
However, when we want to call the method add(), we need an instance of the class MyClass:
class_instance = MyClass()
print(class_instance.add(1, 2))
Notice that when we want to call the add() method, we first have to create a new instance of the class, then use that to call the method, Under the hood, python takes the class_instance variable and passes it to the method as the 'self' argument seen in the function definition.
In closing, your issue is in the line:
event = Event.createEvent()
The error is telling you that the method is expecting an instance of an event class, and not the class itself. If the Event class can be instantiated without arguments, then the correct syntax would be:
base_event = Event()
event = base_event.createEvent()
Of course, the method of instantiating the base_event variable will depend on the API you're trying to use.

How to do yaml.safe_dump() and .safe_load() of Python object without yaml.YAMLObject?

I want to serialize some object with yaml.safe_dump(). How can I serialize Python objects with add_representer() and add_constructor() ...
I can not add yaml.YAMLObject to Thing (third party module) and not want use.
I do such dump:
import yaml
class Thing(object):
def __init__(self, name):
self.name = name
def Thing_representer(dumper, data):
return dumper.represent_mapping('!Thing', data.__dict__)
yaml.SafeDumper.add_representer(Thing, Thing_representer)
safe_dump = yaml.safe_dump(t)
print safe_dump
It works fine but I have no idea how to do constructor?
def Thing_constructor(loader, data):
thing = Thing()
return thing.__dict__.update(loader.construct_mapping(data))
yaml.SafeLoader.add_constructor('!Thing', Thing_constructor)
yaml.safe_load(safe_dump)
It throws exception TypeError: __init__() takes exactly 2 arguments (1 given) and should throw since constructor requires parameters. Maybe there is another option to construct object skipping constructor?
You cannot construct Thing() without handing in the name. You can solve that
in various ways, but the following should work.
def thing_constructor(self, node):
name = None
for x in node.value:
if x[0].value == 'name':
name = x[1].value
return Thing(name)
yaml.SafeLoader.add_constructor('!Thing', thing_constructor)
res = yaml.safe_load(safe_dump)
print res.name
You can simplify the setting of the name parameter, but this way it is more extensible if Thing would have taken more parameters.

Communicating between objects in Python

I have something like this:
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def callDefDoSomething(self):
print exampleClass.doSomething(5)
exampleClass2.callDefDoSomething()
-
TypeError: unbound method callDefDoSomething() must be called
with exampleClass2 instance as first argument (got nothing instead)
I started to learn about objects in Python but i cant find solution for this :(
You need to create an instance of the class, i.e., an active object, to make things work:
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def __init__(self):
self.member1 = exampleClass()
def callDefDoSomething(self):
print self.member1.doSomething(5)
object2 = exampleClass2()
object2.callDefDoSomething()
doSomething is a method of exampleClass. Therefore, it has to be called for an instance of this class.
In callDefDoSomething, you use
exampleClass.doSomething(5)
exampleClass, however, is not an instance of this class but the class itself. What you want to use here is
self.doSomething(5)
self refers to the instance of exampleClass2, for whichcallDefDoSomethingsis invoked, which, due to inheritance, is an instance ofexampleClass`.
Regular class methods can only be called for instances not for classes. So if you want to call callDefDoSomething you have to first instantiate exampleClass2. You also have to instantiate exampleClass inside the call to callDefDoSomething.
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def callDefDoSomething(self):
exampleClassInstance = exampleClass()
print exampleClassInstance.doSomething(5)
exampleClass2Instance = exampleClass2()
exampleClass2Instance.callDefDoSomething()
If you want to call methods on classes you should try classmethods. Check the documentation on classes in the python tutorial.
You can use this:
class exampleClass(object):
def doSomething(self,number):
return number + 1
class exampleClass2(exampleClass):
def callDefDoSomething(self):
print super(exampleClass2,self).doSomething(5)
example = exampleClass2()
example.callDefDoSomething()

Categories