Why does this Python class code cause a syntax error? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
class Song(object):
def _init_(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["heyhey","hey"])
bulls_on_parade = Song(["They rally around the family","hey"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
Hi I'm learning python using learnpythonthehardway. I am getting error in this code and unable to figure out my mistake. Please guide me , i'm a beginner in Python

I don't think you missed the indentation, it is possible that the problem occurred at the time of copy the code to stack overflow. So, i am ignoring these problems.
So, let's fix indentation and run your code.
class Song(object):
def _init_(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["heyhey","hey"])
bulls_on_parade = Song(["They rally around the family","hey"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
I am getting the following error message:
Traceback (most recent call last):
File "/home/ahsanul/Downloads/PythonThreads/threading2.py", line 26, in <module>
happy_bday = Song(["heyhey","hey"])
TypeError: object() takes no parameters
So, the main problem you have is defining the __init__ . You are writing _init_ instead of __init__. If you know the purpose of it, the problem would become clear to you.
__init__ is called when a class object is initialized. By writing __init__ inside your class, you will actually overriding the default one.
So, you have added a parameter lyrics in your _init_ so that you can pass an argument at the time of object initialization, right?
But your function would never be called, that because __init__ is called at the time of initialization, not _init_
So, the default __init__ will be called every time, which has no parameter and at the time of object initialization, you always get an error.
Just change your _init_ to __init__ and you will listen the sweet little song like me.
heyhey
hey
They rally around the family
hey

You are missing indentation inside the class.
And you need to defined method __init__, not _init_.
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
Python is sensitive to indentation.

Related

How to use any obtained variable from a function in other functions in Python classes? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 21 days ago.
Improve this question
I am trying to use one variable obtained from one function in other function. However , it gives error. Let me explain it wih my code.
class Uygulama(object):
def __init__(self):
self.araclar()
self.refresh()
self.gateway_find()
def refresh(self):
self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2, iface="eth0",
retry=3)
#There are unrelated codes here
def gateway_find(self):
#Find ip any range in which you conncet:
self.ip_range=conf.route.route("0.0.0.0")[1]
self.ip_range1=self.ip_range.rpartition(".")[0]
self.ip_range2=self.iprange_1+".0/24"
When , run the foregoing codes , i get this error AttributeError: 'Uygulama' object has no attribute 'ip_range2'
How can i use such variable which are obtained from other function in the other function. How can i fix my problem ?
Call order of init functions
Place function that define attribute first
In the __init__ function, you call refresh, who use (need) ip_range2 before gateway_find who create the attribute and set a value to it. Swap the two lines, you should be fine.
def __init__(self):
self.araclar()
self.gateway_find() # gateway_find will set the ip_range attribute
self.refresh() # So refresh function will be able to access it
Usually, we place init functions first, then function that will call post-init processes like refresh.
Class attribute default value
Alternatively, you can define a default value for ip_range2 like this:
class Uygulama(object):
ip_range2 = None
def __init__(self):
self.araclar()
self.refresh()
self.gateway_find()
def refresh(self):
self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2, iface="eth0", retry=3)
Be aware that such default value is shared with all other instances of the class if not redefined in __init__, so if it's a mutable (like a list), it might create really weird bugs.
Usually, prefer defining value in the __init__ like you do with the gateway fct.
That error explains correctly that you do not have a class attribute called ip_range2. You need to define the class attribute first.
class Uygulama(object):
ip_range2 = ''
...
then use that with self.ip_range2.

Why do I receive the following AttributeError when testing a class method with unittest: 'class' object has no attribute 'testing method'?

For the sake of practicing to code, I am trying to program a very simple game. When trying to run a test on a (private) class method, I receive the following error: AttributeError: 'LivingBeing' object has no attribute '_Test_Class_Methods__lose_hp'
More elaborate:
I have a class named "LivingBeing" in the file classes.py.
class LivingBeing:
def __init__(self, name, hp=100):
self.name = name
self.hp = hp
def __lose_hp(self, number=20, decimal_percentage=1):
self.hp = self.hp - (21 - number)*decimal_percentage
return self.hp
Now I would like to test said __lose_hp method, and I tried this with the following code:
import sys, unittest
sys.path.append("/Users/angel/OneDrive/Dokumente/Studium/CL/Programmieren/git_projects/fantasticgame/")
from classes import LivingBeing
class Test_Class_Methods(unittest.TestCase):
def setUp(self):
self.livingbeing = LivingBeing("Life")
def test_lose_hp(self):
self.assertEqual(self.livingbeing.__lose_hp(20), 99, "Should be 99")
if __name__ == "__main__":
unittest.main()
What I tried so far:
I found some information that it was most likely an ImportError, so I
tried the "sys.path.append"-statement according to how a similar
problem was solved. So, if I were to leave it out, I would receive
the same error message. The file "classes.py" and the testing file
are in this same folder.
At first, I did not have the setUp method, however it had solved a somewhat similar
problem for someone else (namely here), so I tried it - same error message for
me however.
I also didn't have the return statement in the class method itself at
first, about which I very much understand why it would throw an Error
by now (because the return value would be None).
The very classic try to just restart (the computer) and retry before posting also did not help.
There was a point at which I tried to make "Test_Class_Methods"
inherit from both, the unittest.Testcase and LivingBeing, but this
caused the same error again.
Looked like this:
class Test_Class_Methods(unittest.TestCase, LivingBeing):
def setUp(self):
self.livingbeing = LivingBeing("Life")
def test_lose_hp(self):
self.assertEqual(self.livingbeing.__lose_hp(20), 99, "Should be 99")
This being my first question, I hope it's as complete and concise as it should be, and I am thankful for any pointers to help with said error.
EDIT: I changed the method to being public instead of private, and with that change, it now works. If I happen to find a good guide on how to write tests for private methods, I might link it here for future answer-seekers.
I know it's a bit too late but I was facing the same AttributeError as yours.
Removing double underscore from the beggining of the function I wanted to test helped me.

Why does __init__ call the parent class's __init__ before the derived class's __init__?

I am using the cantera module in python, specifically trying to extend the class cantera.Solution using inheritance. The base class can be called like this:
gas = cantera.Solution("gri30.ct")
Where "gri30.cti" is the file name of the chemistry model to be used.
I am trying to make a new class, SolutionExtended which inherits from cantera.Solution. Here is the class definition:
class SolutionExtended(cantera.Solution):
def __init__(self):
print("Beginning of SolutionExtended.__init__")
super().__init__("gri30.cti")
print("End of SolutionExtended.__init__")
When instantiating the SolutionExtended object, I get this error:
Traceback (most recent call last):
File "E:\Projects\Coursework\Cantera\Code\test.py", line 15, in <module>
gas = SolutionExtended()
File "interfaces\cython\cantera\base.pyx", line 63, in cantera._cantera._SolutionBase.__cinit__
ValueError: Arguments are insufficient to define a phase
This is the same error that is thrown when you try to instantiate the parent class cantera.Solution without any input arguments (gas = cantera.Solution()).
Additionally, neither of the print statements actually print.
This leads me to thinking that cantera.Solution.__init__ is being called before SolutionExtended.__init__, which fails because no input arguments are supplied. I am by no means a python expert, however, so this may be completely off.
Can anyone tell me what is going on here? How would I make the SolutionExtended initialization work without requiring the chemistry model to be explicitly input?
I'm pretty stumped by this, so I really appreciate any help. Thanks!
Here is my full code:
import cantera
gas = cantera.Solution('gri30.cti')
gas()
class SolutionExtended(cantera.Solution):
def __init__(self):
print("Beginning of SolutionExtended.__init__")
super().__init__("gri30.cti")
print("End of SolutionExtended.__init__")
gas = SolutionExtended()
gas()
Link to the cantera package website: https://cantera.org/

Missing arguement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I initialised weatherreport.Weather to self.weather in the main file which is responsible for my basic main window.
See the image [![here][1]][1]
def __init__(self):
self.root = tk.Tk()
#Initialize Weather module
self.weather = weatherreport.Weather()
def show_weather(self):
city_name = tk.Entry(self.root, text = "Enter city name : ", width = 15)
self.weather(city_name)
def __init__(self, city):
self.base_url = "http://api.openweathermap.org/data/2.5/weather?"
self.city = city```
U can clearly come to know what error I'm facing. I searched all over internet or atleast what i can. None explains this. I'd love to rectify this but i need some help here. It is a small side project for my internals.
Thanking you in anticipation
[1]: https://i.stack.imgur.com/KLRqQ.png
Welcome to Stack Overflow. Please remember to paste code instead of images of code so it is easier to help you.
Your error is a simple and self-explanatory one. The error is: TypeError: __init__() missing 1 required positional argument: 'city'. Let's break it down.
__init__() is a special function of classes in Python, sometimes called the "constructor". This function gets called when you create an "instance" or "object" of that class.
For example, if I have the following dummy class:
class Foo:
def __init__(self):
print("bar")
When I create an instance of Foo by doing something like x = Foo(), then __init__() gets called and I should see "bar" get printed before the assignment happens.
The error is telling us that this special function of the Weather class is expecting an argument, but never got it. If you look at the __init__ function for the Weather class, you will see that it takes in a parameter called "city".
So to fix this, you have to give provide the arguments to __init__ when creating your class. Something like
self.weather = weatherreport.Weather("Detroit")
I can't really see the error properly, you should post the error and the code as text and not as an picture.
But your __init__ calls two arguments. self and city.
So you should inicialize it with those two arguments. From the error it seems like you only have 1 argument in the function.

How do I call a base class method from within the same overloaded derived class method in python?

I have the following classes setup in my python project,
In MicroSim.py
class MicroSim:
def __init__(self, other_values):
# init stuff here
def _generate_file_name(self, integer_value):
# do some stuff here
def run(self):
# do some more stuff
self._generate_file_name(i)
In ThresholdCollabSim.py
from MicroSim import MicroSim
class ThresholdCollabSim (MicroSim):
# no __init__() implmented
def _generate_file_name(self, integer_value):
# do stuff here
super(ThresholdCollabSim, self)._generate_file_name(integer_value) # I'm trying to call MicroSim._generate_file_name() here
# run() method is not re-implemented in Derived!
In MicroSimRunner.py
from ThresholdCollabSim import ThresholdCollabSim
def run_sims(values):
thresholdSim = ThresholdCollabSim(some_values) # I assume since ThresholdCollabSim doesn't have it's own __init__() the MicroSim.__init() will be used here
thresholdSim.run() # again, the MicroSim.run() method should be called here since ThresholdCollabSim.run() doesn't exist
When I run this code I get the error msg,
Traceback (most recent call last): File "stdin", line 1, in
File "H:...\MicroSimRunner.py", line 11, in run_sims
thresholdSim.run() File "H:...\MicroSim.py", line 42, in run
self._generate_file_name(r) File "H:...\ThresholdCollabSim.py", line 17, in _generate_file_name
super(ThresholdCollabSim, self)._generate_file_name(curr_run) TypeError: unbound method _generate_file_name() must be
called with MicroSim instance as first argument (got int instance
instead)
I have tried searching for issues like this here and have found similar posts and have tried all the solutions discussed there but this error doesn't seem to go away. I have tried changing the line in question to,
super(ThresholdCollabSim, self)._generate_file_name(self, curr_run)
but it changes nothing (same error). I am relatively new at Python programming so this may just be a silly mistake. Any help is much appreciated. Thanks!
You forgot the self argument in your derived _generate_file_name method. Also, you need to make MicroSim a new-style class by using class MicroSim(object).
As a supplement.
You use super in the old-style class.
From the super documentation, we know that:
super() only works for new-style classes.
And a new-style class is
Any class which inherits from object.

Categories

Resources