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 have a module call pcb_files.py that only have some imports like this -> import read
Then I have another module call Easy.py, that have a class (Mainwindow) and a method/funtion (function_pcb1)
Class MainWindow(xxx,xxx)
.....
.....
def func_pcb1(self):
pcb_files.read.main(self)
Right now everytime I press a pushbutton in my app I run the funtion "main" that is inside "read". So far so good
What I want:
def func_pcb1(self):
script=self.nome_do_script
pcb_files.script.main(self)
Like you see in, now I have this : script=self.nome_do_script where "script" is a string type.
And now I just want to change one thing, in the place of "read" I want to put the "script" like i do in the image but it gives me an error -> AttributeError: module 'pcb_files' has no attribute 'script'
Resuming, instead of call whats inside "script" variable, it's calling the name script itself.
Now you're asking why do you want that ? -> Answer: I want to call, and show to the user, in my app different files that will do different things
something.other is what Python calls attribute access, where "other" is the attribute name. If you want to access an attribute with a dynamic name, you can use getattr.
def func_pcb1(self):
script = self.nome_do_script
getattr(pcb_files, script).main(self)
In the long term, you'll want to learn how to use dictionaries for these kinds of things.
Related
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
My code:
import requests
class weatherapi:
def __init__(self,api_url,string,zipcode):
self.api_url = 'https://api.openweathermap.org/data/2.5/weather?zip=10502,us&appid=50b55ef1602086c74b71f56c6df14996'
self.input = string
self.zipcode = zipcode
def get(self):
get_weather = requests.get(self.api_url)
json_weather = get_weather.json()
def response(self):
national = requests.get('https://api.openweathermap.org/data/2.5/weather?zip='+self.zipcode+',us&appid=50b55ef1602086c74b71f56c6df14996')
json_national = national.json()
kelvin = float(national.json['main']['temp'])
return str(kelvin)
from weatherapi import weatherapi
def main():
zipcode = input('Please input your zip code ')
weatherapi.response(zipcode)
I get attributeError: 'str' object has no attribute 'zipcode' when running this code. I have no idea why this is happening, could somebody explain why?
The function .response does not take any arguments aside from the reference to the object ("self").
You need to first construct an instance of the class before you can use the .response() function. You'll need something like `my_weatherapi = weatherapi('https://www.some.url.com/', 'some_input_string', 90210).
Also, the error code is AttributeError, not tributeError.
All in all, there are a lot of mistakes in this. I would recommend you go through a Python tutorial first; specifically look into defining classes and using constructors and class functions.
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 4 years ago.
Improve this question
class Pract:
p1 = Pract() #creating an instance of Pract
p1.age=45 #creating a field-variable
print(p1.age)
I checked this Youtube, in the video its shows as working, but I couldn't run it.
# First declare a class (empty, in this case)
class Pract:
pass
# Then instantiate it
p1 = Pract()
# Then set the attribute
p1.age = 45
# Then print the attribute
print(p1.age)
You cannot instantiate a class before you finish declaring it. Everything you put inside class is part of the class definition. You have to de-indent your code in order to mark the end of the class definition.
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 4 years ago.
Improve this question
Easy question, is it possible to remove an object from memory and setting all remaining pointers to it to undefined?
You cannot explicitly free memory in Python.
If you want to call del x without having other references to x preventing it from getting garbage collected, you may want to check out weakrefs.
In case you are looking to create some sort of 'cancelable' object that can be invalidated and cause all subsequent attempts to use it to get either a None value or an error, you can do that (after a fashion), but your code will have to be disciplined not to get a direct reference ever, but always refer to the object in a special way, for example:
class deletable(object):
def __init__(self, value):
self.v = value
def destroy(self):
if hasattr(self,"v"): delattr(self, "v")
# create instance
x = deletable( { "key" : "value", "other" : 13 } )
# access
print (x.v["key"])
# re-assign
x.v = { "another" : "dict" }
# "destroy" - option 1 - trigger error on use
x.destroy()
# "destroy" - option 2 - make it None (free memory, but keep x.v valid)
x.v = None # or x.v = {}, if you want to keep it with the original data type of dict()
Now, this "works" on the condition that you never (EVER) do z = x.v and always pass around x as a whole.
(If you know in advance the data type and it is always the same, e.g., dict, you can do a bit better and have the custom object respond to things like x["key"], x.update(some_dict), etc., i.e., look like a regular dict, but still able to call x.destroy() and make it fail further attempts to access. Advanced stuff, I won't write a whole article here on this, not even knowing that I made a correct guess as to what you really need).
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 5 years ago.
Improve this question
I want to import a module named "config" and I want import config.times. But in my code, times is a element in a list name_list, it means:
name_list = ['times','date','hours'].
When I want to use config.times ,I try config.name_list[0]. Of course there is an error " 'module' object has no attribute 'name_list'". So how can I fix it? Thanks.
---More details:
My code is: config.py,main.py .In config.py, times = ['00:00:00','12:00:00'],and in main.py ,name_list = ['times','date','hours'],I want exec now = config.times in main.py.
If I understand correctly, you want to access the times variable from a module you've imported, but you want that name (times) to come from another variable, rather than being hard coded.
That's possible to do in a few ways. The easiest is probably to use the getattr function to get the attribute from the module object:
import config
name = "times" # or wherever, e.g. name_list[0]
results = getattr(config, name) # will get a reference to config.times
I'm not sure doing this is really a great idea though. Generally speaking, variable names (such as times in the config module) should be intended for programmers to interpret. They should not be data. If you want to look up data by name, you should generally use a dictionary to store the keys and values, rather than using the namespace of a module.
So for instance, your config module could have a dictionary named data, and you could move your current times value to data['times']. Then looking up a value by name is just a dictionary lookup: config.data[name].
Try using following in main.py :
from config import times
or
name_list = ['config.times','date','hours']
EDITED from here on for more clarification
and then use :
eval(name_list[0]) # for evaluating config.times
I hope this is more clear
please remove the downvote.
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 8 years ago.
Improve this question
Is there a way in Python 3.x to create a new type? I can only find ways to do it in c++. (I don't mean adding/editing syntax by the way)
Basically what I want to do is create a lexer, where I scan input and python can already do int and string, but if I want another datatype such as name, how could I assign it so that I can do...
Example:
# This can be done
a = "string"
type(a)
> <class, 'str'>
# How can I do this?
b = myName
type(myName)
> <class, 'name'>
You would want something like this, a class. In the source code all of the object types you see in Python are in class form.
>>> class myName:
... def __init__(self, name):
... self.name = name
... def __str__(self):
... return self.name
...
>>> b = myName('John')
>>> type(b)
<class '__main__.myName'>
>>> print(b)
John
The reason the output is slightly different to what you expected is because the name of the class is myName so that is what is returned by type(). Also we get the __main__. before the class name because it is local to the current module.
You might have a look at Metaclasses: http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/
However, what exactly do you want to achieve?
The short answer is you can't make a new type in python without editing the source code (written in C).
However the answer about creating a class in python is probably the easier route to go since editing the source can create compatibility problems with packages (potentially speaking).