I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result.
Step 1:
Code:
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
Step 2:
ctrl + B
Step 3:
Result:
Repl Closed
That's because you're only declaring a class, not instantiating it.
Your variable avenger1 exists within the init function, therefore it isn't being called. Indentation matters in python.
Try this:
class Avengers(object):
def __init__(self):
print('hello')
if __name__ == "__main__":
avenger1 = Avengers()
You are not instantiating the class. Try something like:
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
When you instantiate a class like this, it will execute the __init__ function for that class.
First, let me fix the code
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
okay, here you creating a class called Avengers. why its not produce anything? because you never initialize that class (creating an object).
so here we go:
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers()
avenger1.init(self)
Avengers()
it will printing hello, but, its recursive. never end printing "hello". because each time that class is initialized, its creating an object again again and again. init is special function so, each time the class is initialized, init function will executed.
maybe what you want is like this:
class Avengers(object):
def __init__(self):
print('hello')
Avengers()
additional reference that you can read: https://www.sololearn.com/Play/Python
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers.
This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on.
The __init__ function is falling into an infinite recursion.
class Avengers(object):
def __init__(self):
print('hello')
avenger1 = Avengers() # this line triggers infinite recursion
avenger1.__init__(self)
avengers = Avengers() # Initiates the class
Related
I have a little problem, I have my code below.
I want to call the "speak" function with two arguments inside the main() class.
When I call speak it says that self its not defined, and i don't know how to make it work...
Any ideas?
class main():
def blueon(self):
print("teste")
def speak(self,fala):
self.blueon
print(fala)
speak("testeaaaaa")
Try something like this.
Comments explain changes
class Main: # Class name capitalized and no parenthesis if the class has no base classs
def __init__(self): # class constructor. Initialize here your variables
pass
# if you have a function that doesn't use self, you can declare it static
#staticmethod
def blueon():
print("teste")
def speak(self, fala):
self.blueon() # added missing parenthesis
print(fala)
if __name__ == "__main__": # add this so you can later import your class as a library without executing your test code
m = Main() # instantiate the class
m.speak("testeaaaaa") # call the speak method
You run speak() in wrong way.
First you have to create instance of class m = main() and later use m.speak("text").
And you have to do with different indetation.
BTW: There is good rule to use CamelCaseName for classes - class Main(): - it helps to recognize class in code, and it allows to do main = Main().
More in PEP 8 -- Style Guide for Python Code
# --- classes ---
class Main():
def blueon(self):
print("teste")
def speak(self, fala):
self.blueon() # you forgot `()
print(fala)
# --- main ---
main = Main()
main.speak("testeaaaaa")
I have some code that creates instances from a list of classes that is passed to it. This cannot change as the list of classes passed to it has been designed to be dynamic and chosen at runtime through configuration files). Initialising those classes must be done by the code under test as it depends on factors only the code under test knows how to control (i.e. it will set specific initialisation args). I've tested the code quite extensively through running it and manually trawling through reams of output. Obviously I'm at the point where I need to add some proper unittests as I've proven my concept to myself. The following example demonstrates what I am trying to test:
I would like to test the run method of the Foo class defined below:
# foo.py
class Foo:
def __init__(self, stuff):
self._stuff = stuff
def run():
for thing in self._stuff:
stuff = stuff()
stuff.run()
Where one (or more) files would contain the class definitions for stuff to run, for example:
# classes.py
class Abc:
def run(self):
print("Abc.run()", self)
class Ced:
def run(self):
print("Ced.run()", self)
class Def:
def run(self):
print("Def.run()", self)
And finally, an example of how it would tie together:
>>> from foo import Foo
>>> from classes import Abc, Ced, Def
>>> f = Foo([Abc, Ced, Def])
>>> f.run()
Abc.run() <__main__.Abc object at 0x7f7469f9f9a0>
Ced.run() <__main__.Abc object at 0x7f7469f9f9a1>
Def.run() <__main__.Abc object at 0x7f7469f9f9a2>
Where the list of stuff to run defines the object classes (NOT instances), as the instances only have a short lifespan; they're created by Foo.run() and die when (or rather, sometime soon after) the function completes. However, I'm finding it very tricky to come up with a clear method to test this code.
I want to prove that the run method of each of the classes in the list of stuff to run was called. However, from the test, I do not have visibility on the Abc instance which the run method creates, therefore, how can it be verified? I can't patch the import as the code under test does not explicitly import the class (after all, it doesn't care what class it is). For example:
# test.py
from foo import Foo
class FakeStuff:
def run(self):
self.run_called = True
def test_foo_runs_all_stuff():
under_test = Foo([FakeStuff])
under_test.run()
# How to verify that FakeStuff.run() was called?
assert <SOMETHING>.run_called, "FakeStuff.run() was not called"
It seems that you correctly realise that you can pass anything into Foo(), so you should be able to log something in FakeStuff.run():
class Foo:
def __init__(self, stuff):
self._stuff = stuff
def run(self):
for thing in self._stuff:
stuff = thing()
stuff.run()
class FakeStuff:
run_called = 0
def run(self):
FakeStuff.run_called += 1
def test_foo_runs_all_stuff():
under_test = Foo([FakeStuff, FakeStuff])
under_test.run()
# How to verify that FakeStuff.run() was called?
assert FakeStuff.run_called == 2, "FakeStuff.run() was not called"
Note that I have modified your original Foo to what I think you meant. Please correct me if I'm wrong.
I am coding a simple game of tic-tac-toe. My function to check winning is too repetitive and big, so I want to put it into an external file. My idea is:
class Game(object):
def __init__(self):
pass
import funcFile
instance = Game()
instance.func()
While in funcFile.py is:
def func():
print("Hello world!")
But:
Traceback (most recent call last):
instance.func()
TypeError: 'module' object is not callable
Is there a way to do this, or should I put everything in one file?
There are many ways to solve this kind of problem.
The most straightforward solution (which is what I think you had in mind) is to factor out the implementation of the func method to a separate module. But you still need to define the method in the class.
main.py:
from func_module import func_implementation
class Game: # note: you don't need (object)
def __init__(self):
pass
def func(self):
return func_implementation()
instance = Game()
instance.func()
func_module.py:
def func_implementation():
print('hello')
Another approach would be to factor out the func method to another class which the Game class inherits. This pattern is also known as a mixin class:
main.py:
from func_module import FuncMixin
class Game(FuncMixin):
def __init__(self):
pass
instance = Game()
instance.func()
func_module.py:
class FuncMixin:
def func(self):
print('hello')
But this is less clear, as you can't immediately see that the Game class has a func method and what it does. Also you can introduce subtle bugs with multiple inheritance if you're not careful. So in your case I'd prefer the first approach.
You should try from funcFile import func in your main file:
from funcFile import func
class Game(object):
def __init__(self):
pass
import funcFile
instance = Game()
instance.func()
I am trying to access to another variable that inside a function and also that is from another class, so I coded it in that way
class Helloworld:
def printHello(self):
self.hello = 'Hello World'
print (self.hello)
class Helloworld2(Helloworld):
def printHello2(self)
print(self.hello)
b = Helloworld2()
b.printHello2()
a = Helloworld()
a.printHello()
However, this gives me that error: AttributeError: 'Helloworld2' object has no attribute 'hello'. So, what would be the simplest way to access to that variable?
That's because you never call printHello(self) that declare your self.hello.
To make it work you need to do:
class Helloworld2(Helloworld):
def printHello2(self):
super().printHello()
print(self.hello)
Or move declaration of you self.hello to __init__() which would be more preferred way.
You should initialise the instance of the class via the __init__() function, this means that when it is created, these values are set.
That would make your code look like:
class Helloworld:
def __init__(self):
#sets self.hello on creation of object
self.hello = 'Hello World'
def printHello(self):
print (self.hello)
class Helloworld2(Helloworld):
def printHello2(self):
print(self.hello)
b = Helloworld2()
b.printHello2()
a = Helloworld()
a.printHello()
An alternative, with your current code is to just call printHello(), either at the top level, with b.printHello(), or within printHello2. Note that in this case, you don't actually need to use super().printHello() as you are not re-defining that function in Helloworld2, though it would be required if you did.
I am trying to create a class called ListenerVilma that has two methods: "Clock_" and "Diagnostics_". Nevertheless both methods will call inner functions. The following code shows my attempt to achieve the mentioned behavior, but when I call ListenerVilma.Clock_() the get the following error:
TypeError: unbound method Clock_() must be called with ListenerVilma instance as first argument (got nothing instead)
How should a create my class ListenerVilma???
Thanks.
#!/usr/bin/env python
import rospy
from rosgraph_msgs.msg import Clock
from diagnostic_msgs.msg import DiagnosticArray
class ListenerVilma:
"""Class that listens all topics of the file vilmafeagri"""
def Clock_(self):
"""Method that listens the topic /clock if the file vilmafeagri"""
def __init__(self):
self.listener()
def callback(self, clock):
print clock
def listener(self):
rospy.Subscriber('clock', Clock, self.callback)
def Diagnostics_(self):
"""Method that listen the topic /diagnostics from rosbag file vilmafeagri"""
def __init__(self):
self.listener()
def callback(self, diagnostics):
print diagnostics
def listener(self):
rospy.Subscriber('diagnostics', DiagnosticArray, self.callback)
if __name__ == '__main__':
rospy.init_node('listener', anonymous=True)
ListenerVilma.Clock_()
rospy.spin()
the error is in line 41 in ListenerVilma.Clock_() here your directly using the method of your class so no implicit argument is pass and a instance of ListenerVilma is expected. The solution is ListenerVilma().Clock_() this first create a instance of your class and from say instance call its Clock_ method.
Outside that, your class construction is very weird, the __init__ is used to initialize a class and a basic class construction is like this
class Foo:
"""example class"""
def __init__(self,*argv,**karg):
"""initialize this class"""
#do something with argv and/or karg according to the needs
#for example this
print "init argv", argv
print "init karg", karg
self.ultimate=42
def do_stuff(self):
"""this method do something"""
print "I am doing some stuff"
print "after 7.5 million years of calculations The Answer to the Ultimate Question of Life, the Universe, and Everything is: ", self.ultimate
def do_some_other_stuff(self,*argv,**karv):
"""this method do something else"""
print "method argv", argv
print "method karg", karg
# basic usage
test = Foo(1,2,3,key_test=23)
test.do_stuff()
test.do_some_other_stuff(7,8,9,something=32)
test.ultimate = 420
test.do_stuff()
I am not quite sure what you intentions are, but you build Clock_ and Diagnostics_ as a class, but they are not, and as right now they do nothing, if you want they to be class on their own do
class Clock_:
def __init__(self):
self.listener()
def callback(self, clock):
print clock
def listener(self):
rospy.Subscriber('clock', Clock, self.callback)
and the same with Diagnostics_, and I don't see a reason to the listener method so I would put what it does in the __init__, but maybe the rospy need it? I don't know, but for the looks of it then it should be used as
rospy.init_node('listener', anonymous=True)
Clock_()
Diagnostics_()
rospy.spin()
The Clock_ method doesn't belong to the class; it's an 'instance' method.
There are two options
In the main function: create an instance of ListenerVilma: listener = ListenerVilma(), or
In the ListenerVilma class: annotate the methods with #classmethod and make the class inherit from object: class ListenerVilma(object):. But remember, the first argument in your methods will be a reference to the class and not a reference to an instance.
The following code performs better the behavior that I wanted. :)
class ListenerVilma:
def CLOCK(self):
def clock_sub():
rospy.Subscriber('clock', Clock, clock_callback)
def clock_callback(clock):
print clock
clock_sub()
def DIAGNOSTICS(self):
def diagnostics_sub():
rospy.Subscriber('diagnostics', DiagnosticArray, diagnostics_callback)
def diagnostics_callback(diagnostics):
print diagnostics
diagnostics_sub()
if __name__ == '__main__':
rospy.init_node('listener', anonymous=True)
myVilma = ListenerVilma()
myVilma.CLOCK()
myVilma.DIAGNOSTICS()
rospy.spin()