Missing arguement [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 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.

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.

Using class variables in methods of the same class in Python [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 1 year ago.
Improve this question
I am currently learning Python at home using the Python for Dummies all in one book. I'm on the chapter about classes and in particular the section on class variables. So far, the code has been running fine, but I'm not sure why it doesn't work the way I expect.
My code is this:
class Crew_Member:
"""A class for creating an individual record"""
is_human = True
def __init__(self, full_name, username, rank="crewmember"):
self.full_name = full_name
self.username = username
self.rank = rank
self.join_date = dt.date.today()
def file_age(self):
return f"{self.full_name}'s file was created on {self.join_date:%d/%m/%y}"
def promote(self, rank):
self.rank = rank
def not_human(self):
if Crew_Member.is_human:
self.rank = "Mech/Scutter"
So my understanding is that is_human is the class variable. The method I'm trying to use it in is not_human. The idea is that each object would be the personel record for a crew member. If that crew member is not human, they automatically get the rank of "Mech/Scutter".
The way I imagined it working is after the object has been called, you change that instance's value of is_human to false, run the method not_human, and that would change their rank accordingly. The first time I tried and got the correct rank, the class variable hadn't changed:
My code (as written above) works fine, but this is what I have to enter to get it to work:
So this is my problem: The for (edit: if) loop in the not_human method says "If class variable is true, then change rank". But the class variable has been changed to false (as illustrated by the first print line) so why does it work?
But the class variable has been changed to false...
No, the line BobScutt.is_human = False turns it into an instance variable. The class variable remains untouched. If you want to change it, you have to manipulate the Crew_Member class directly, not one of its instances.
Observe:
class TestClass:
test_attr = True
foo = TestClass()
foo.test_attr = False
print("Test attribute in foo:", foo.test_attr)
print("Test attribute in TestClass:", TestClass.test_attr)
Output:
Test attribute in foo: False
Test attribute in TestClass: True

get() takes 1 positional argument but 2 were given when trying to override save method in django [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 1 year ago.
Improve this question
how to fix this?
from django.db import models
import pycountry
# Create your models here.
class Country(models.Model):
country_name = models.CharField(max_length=50)
code = models.CharField(max_length=3, editable=False)
def save(self, *args, **kwargs):
country_list = []
for country in pycountry.countries:
country_list.append(country.name)
if (self.country_name in country_list):
self.code = pycountry.countries.get(self.country_name).alpha_3
super(Country, self).save(*args, **kwargs)
I peeked at the pycountry API. The get method signature on the countries object ultimately looks like this:
def get(self, **kw):
...
In Python speak that means it only accepts "named" arguments. In your code, you're giving the country_name as a positional argument.
I couldn't infer from my quick glance at the code what they're expecting you to pass, but from context I'm guessing it's something like this:
self.code = pycountry.countries.get(name=self.country_name).alpha_3
Notice the slight difference where your argument is explicitly named, not just passed positionally.
This error itself is always a tad confusing because of self. Python instance methods always have self as an implicit positional argument. It's telling you that self is the only valid positional argument (1), but you are passing both self and country_name positionally (2).

Why does this Python class code cause a syntax error? [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 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.

TypeError: functionname() takes exactly 2 arguments (1 given)

I'm trying to pass a dictionary that was initialized in one class as an argument into a method in another class. I wrote this code but no matter how I try to fix it I can't get going to test my other code..
I was trying to pass myDict as an argument in functionname by having class B inherit class A (I'm going to have other classes that will inherit class A and will have a function that takes myDict as an argument as well).
I have this:
class A(object):
def __init__(self):
class B(A):
.....
def functionname(self, myDict):
.....
def otherfunction(text):
text = function(otherargument) #this function returns a list and for each item in the list I call functionname.
myDict = {}
for x in text:
x.functionname(myDict)
I thought this would work but when I try to test my other code I get: TypeError: functionname() takes exactly 2 arguments (1 given). Am I not approaching this the right way?
This is homework so I would really appreciate some guidance on understanding the concept of this.
Edit: I called functionname from another function outside of the classes.
The error also starts at the function call (x.functionname()) and says TypeError
Edit: So I tried moving the dictionary that I declared in init to otherfunction and it worked and gave me different errors for other parts of code that needs to be fixed. But for this error, it was solved.

Categories

Resources