It is first time I try to use super(), I tried many little changes to this code, but with all I got error on line where super() is.
I saw similar questions on SO, but they are not working in my case or I do something wrong
Could you help me to call getMessagesBodies() from list() ?
class Gmail:
def getMessagesBodies(self, text):
return self.unpackPayload(text)
def unpackPayload(self, text):
return (text)
class getMessages:
def __init__(self):
self.service = auth()
def list(self,text):
return super(self).getMessagesBodies(text) # error here, how to call getMessagesBodies properly?
The problem is that you never specified what the parent class was for the getMessages class.
You should define the class like so:
class getMessages(Gmail):
Unless your child class is overriding the getMessagesBodies() function, you actually do not have to use super() to specify that you want to call the parent function. By using self.getMessagesBodies() in your child class it will automatically call the parent's function since the child inherits all the same functions from the parent.
So you can call the function without using super like:
self.getMessagesBodies(text)
Also, just a tip is that getMessages seems more like a function name then a class. Usually classes are fully capitalized and are an object, not an action.
Related
Why is it so that when I try to call the Parent class constructor using super(), I don't need to pass 'self' as an argument:
super().__init__(x,y)
Yet when I call it using the Parent class itself (named Parent in this case), a 'self' argument needs to be passed.
Parent.__init__(self,x,y)
(x and y are Parent class attributes here)
Just want to understand the background logic here. Thanks!
This is because super() can only be called inside a class method definition (like in __init__), and it always refers to itself. Therefore, there is no need, it is redundant.
Interesting you mention it: self used to be required just a few years ago (maybe 5... I cannot remember).
Think of it like calling methods. If I have the following class:
class Conversation:
def __init__(self):
pass
def hi(self, name):
print(f'How are you doing, {name}?')
convo = Conversation()
convo.hi('Jason')
(output): 'How are you doing, Jason?'
I did not have to specify self when calling convo.hi, I only had to pass an argument to name. Why? Because self is always needed, and therefore redundant.
Same idea with super(). :)
I am trying to call the methods in CSVDatasource in my testing class by typing this code from ETL.CSVDatasource import CSVDatasource and to call the necessary methods but I have been receiving errors like TypeError: unbound method preprocess_col() must be called with CSVDatasource instance as first argument (got DataFrame instance instead)
http://imgur.com/8sfygtA -> Image of my coding path
Anyone can guide me on calling out the method in the other class so that I can call the method and do testing in my testing classs?
Thanks.
Generally, an instance of the class has to be created before calling the method of the class. For example,
class Person:
def __init__(self,name):
self.name=name
def who(self):
print 'I am {}'.format(self.name)
#staticmethod
def species():
print 'I am human.'
If we want to call the method who inside the class Person, we have to create an instance of class as follows:
if __name__=='__main__':
p1=Person('Qing Yong')
p1.who() #I am Qing Yong
However, if a method doesn't require self but you want to put it inside the class as this method may strongly related to you class in some senses. You may declare it as static method by using the decorator #staticmethod, like the method species
This static method can be called either through instance or through class directly as follows.
if __name__=='__main__':
p1.species() #I am human.
Person.species() #I am human.
Depending on the context of your code, you may choose either way to use the method inside your class.
here is a part of my code :
class projet(object):
def nameCouche(self):
valLissage = float(ui.valLissage.displayText())
return (valLissage)
valCouche = nameCouche() # asks for a positional argument but 'self' doesnt work
def choixTraitement(self):
ui.okLissage.clicked.connect(p.goLissage)
def goLissage(self, valCouche):
if ui.chkboxLissage.isChecked():
print(valCouche) # result is False
os.system(r'"C:\Program Files\FME\fme.exe" D:\Stelios\..... --MAX_NUM_POINTS {0}'.format(valCouche))
So I would like to use valCouche in goLissage method but it doesnt work.
I thought that valCouche would have the argument of valLissage but instead it gives False as a value.
I've tried different alternatives but still doesnt work.
You've got multiple problems here.
First, if you write this in the middle of a class definition:
valCouche = nameCouche()
... you're creating a class attribute, which is shared by all instances, not a normal instance attribute.
Also, you're running this at class definition time. That means there is no self yet--there aren't any instances yet to be self--so you can't call a method like nameCouche, because you don't have anything to call it on.
What you want to do is call the method at instance initialization time, on the instance being initialized, and store the return value in an instance attribute:
def __init__(self):
self.valCouche = self.nameCouche()
Then, when you want to access this value in another method later, you have to access it as self.valCouche.
If you make those changes, it will work. But your object model still doesn't make much sense. Why is nameCouche a method when it doesn't have anything to do with the object, and doesn't access any of its attributes? Maybe it makes sense as a #staticmethod, but really, I think it makes more sense just as a plain function outside the class. In fact, none of the code you've written seems to have anything to do with the class.
This kind of cram-everything-into-the-class design is often a sign that you're trying to write Java code in Python, and haven't yet really understood how Python does OO. You might want to read a good tutorial on Python classes. But briefly: if you're writing a class just to have somewhere to dump a bunch of vaguely-related functions, what you want is a module, not a class. If you have some reason to have instances of that class, and the functions all act on the data of each instance, then you want a class.
You have to declare variabile in the __init__ method (constructor) and then use it in your code
ex:
class projet(object):
def __init__(self):
self.valCouche = ''
def nameCouche(self):
valLissage = float(ui.valLissage.displayText())
return (valLissage)
def choixTraitement(self):
ui.okLissage.clicked.connect(p.goLissage)
def goLissage(self, valCouche):
if ui.chkboxLissage.isChecked():
self.valCouche = self.nameCouche()
print(self.valCouche) # result is False
os.system(r'"C:\Program Files\FME\fme.exe" D:\Stelios\..... --MAX_NUM_POINTS {0}'.format(self.valCouche))
you have to define an initialization function: def__init__(self)
defining valCouche as an instance attribute make it accessible on all the method so we have the following
class projet(object):
def __init__(self):
self.valCouche = ''
def nameCouche(self):
self.valCouche = float(ui.valLissage.displayText())
#staticmethod #here there is no need for self so it is a method of class
def choixTraitement():
ui.okLissage.clicked.connect(p.goLissage)
def goLissage(self):
if ui.chkboxLissage.isChecked():
print(self.valCouche) # result is False
os.system(r'"C:\Program Files\FME\fme.exe" D:\Stelios\..... --MAX_NUM_POINTS {0}'.format(self.valCouche))
I need to call the inherited class to get it's content and methods to work. But I also have a class decorator assigned to my wrapper classes. I have a lot of wrapper classes and want them to be as short as possible, that's why I try to get this to work.
#add_properties
class Item01Object(BaseItemObject):
properties=["quantum","size","mass"]
def __init__(self, name=None):
super(Item01Object, self).__init__(name)
#[...]
#add_properties
class Item02Object(BaseItemObject):
#[...]
But when I instance my class, I get the following error:
File "C:\wrapper.py", line 862, in __init__
super(Item01Object, self).__init__(name)
NameError: global name 'Item01Object' is not defined
The idea:
Quick edit of each "wrapper" item's properties with it's class variable properties
Base functionality given by the BaseItemObject
Methods could be easily overwritten
Short wrapper classes to have a good overview
How could I make it work??
Thanks.
OK. I solved it. Was a really simple mistake. In add_properties I returned the object of my class, but it needs to return the class itself. So my constructor was executed before my class was completely build. So I just changed it to the following and it works fine:
def add_properties( ItemObject ):
for propName, cls in PropertyContainer.__dict__.iteritems():
if propName in ItemObject.properties:
setattr(ItemObject, propName, cls.__dict__[propName])
return ItemObject # <- Do not return an object!!
This is the first time I am using a lot of decorators in a complex structure, but I really like the idea and the structure I get with it.
This simple example is what I dont get to work or understand in my more complex script:
class printclass():
string="yes"
def dotheprint(self):
print self.string
dotheprint(self)
printclass()
When the class is called, I expected it to run the function, but instead it will tell me that "self is not defined". Im aware this happens on the line:
dotheprint(self)
But I dont understand why. What should I change for the class to run the function with the data it already has within? (string)
You misunderstand how classes work. You put your call inside the class definition body; there is no instance at that time, there is no self.
Call the method on the instance:
instance = printclass()
instance.dotheprint()
Now the dotheprint() method is bound, there is an instance for self to refer to.
If you need dotheprint() to be called when you create an instance, give the class an __init__ method. This method (the initializer) is called whenever you create an instance:
class printclass():
string="yes"
def __init__(self):
self.dotheprint()
def dotheprint(self):
print self.string
printclass()
You really need to understand Object-Oriented Programming and its implementation in Python.
You cannot "call" a class like any function. You have to create an instance, which has a lifetime and methods linked to it :
o = printclass() # new object printclass
o.dotheprint() #
A better implementation of your class
class printclass():
string="yes" #beware, this is instance-independant (except if modified later on)
def dotheprint(self):
print self.string
def __init__(self): # it's an initializer, a method called right after the constructor
self.dotheprint()