Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm having some issues with Python as an OO language. I learned OO with Java and Python, while similar, seems to have some key differences. I'm trying to write a basic chatbot (I mean really basic) and for some reason I'm unable to access variables from inside the class. Here is my code:
chatbot.py
import random
class Chatbot:
greetings = ["Hello", "WAZZZZZUUUPPPPP", "Howdy"]
salutations = ["Bye", "Bye Felicia", "Adios", "Fine, I didn't want to talk to you anymore anyway"]
how_are_you = ["I'm good", "I've been better", "Better than you"]
whats_up = ["Not much", "Thinking about life, the universe, and everything", "Just wondering why you're communicating with a human in a box"]
def respond(self,text):
myText = text.lower();
print(text)
if text == "hello":
print(self.greetings[random.randint(0, greetings.length - 1)])
and here's the calling code, rowdy-messenger.py:
from chatbot import Chatbot
print("Welcome to rowdy messenger")
hello = Chatbot()
hello.respond("hello")
The error text I'm getting is (I omitted the absolute path)
...
File "rowdy-messenger.py", line 5, in <module>
hello.respond("hello")
line 15, in respond
print(greetings[random.randint(0, greetings.length - 1)])
NameError: name 'greetings' is not defined
My questions:
1) Why am I getting this error? I'm used to Java where this would be just fine (using this instead of self of course)
2) Is it better to use these as class variables or instance variables? In the calling code it will only be instantiated once anyway but I figured for "large" data it's better to only instantiate constants once.
The problem is that you didn't use self consistently. That line refers to greetings twice; the first time you do use self, but the second time you don't.
Python's "explicit is better than implicit" philosophy means you always need to use self.
Note, though, the code could be simplified to print(random.choice(self.greetings)).
https://syntaxdb.com/ref/python/class-variables
If you're intending for greeting to be an instance variable (it looks like you are), you'll want to also prefix self to the greeting declaration.
This is one of the many differences between python's take on OOP and that of Java (no this necessary in the greeting declaration)
Related
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
Below is the python code that I am trying to use to run a function.
def list_benefits():
return "More organized code", "More readable code", "Easier code
`reuse", "Allowing programmers to share and connect code together"`
def build_sentence(benefit):
return "%s is a benefit of functions!" %benefit
def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefi in list_of_benefits:
print(build_sentence(benefi))
name_the_benefits_of_functions()
I don't understand why do we need to have the variable 'list_of_benefits' and why can't we directly use 'list_benefits' in the last function. The above code runs well, but if I remove 'list_of_benefits' from everywhere, I get the below error -
TypeError: 'function' object is not iterable
You can use list_benefits() in the loop directly. Check out the below code:
def list_benefits():
return "More organized code", "More readable code", "Easier code","reuse", "Allowing programmers to share and connect code together"
def build_sentence(benefit):
return "%s is a benefit of functions!" %benefit
def name_the_benefits_of_functions():
for benefi in list_benefits():
print(build_sentence(benefi))
name_the_benefits_of_functions()
It worked fine for me. Output:
More organized code is a benefit of functions!
More readable code is a benefit of functions!
Easier code is a benefit of functions!
reuse is a benefit of functions!
Allowing programmers to share and connect code together is a benefit of functions!
Please not if you want do this (and I believe most probably you ran into error trying this):
for benefi in list_benefits:
Its not gonna work for you because in such case list_benifits becomes a variable not a function. So it will generate an error.
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 5 years ago.
Improve this question
I am reading https://stackoverflow.com/a/28231805/156458
Why can we give the module name as a variable to builtins.__import__ function,
while we must give the module name directly to the import statement?
What difference between a statement and a function that leads to such a difference?
The same reason you need to give the name of the function to the def statement, or the name of the class to class; both can be created by other means too. Because that's how the syntax is designed, to make common actions possible with readable clear, concice syntax.
For the same reason you use object.attributename when you already know the attribute name you want to access, but use getattr() when you need to determine the name dynamically. The latter is more work for the programmer to understand.
Imagine having to wade through
modules_to_import = ['builtins', 'datetime']
for name in modules_to_import:
globals()[name] = __import__(name)
print_function_name = 'print'
current_time = getattr(getattr(globals()['datetime'], 'datetime'), 'now')()
getattr(globals()['builtins'], print_function_name).__call__('Hello world!, it is now', current_time)
That'd be totally unreadable. Compare that to
import datetime
current_time = datetime.datetime.now()
print('Hello world!, it is now', current_time)
Python is a highly dynamic programming language, however, so you are given tools to do many tasks dynamically. type() lets you build classes dynamically, functions can be constructed without using def or lambda, and you can import modules based on a variable. You use those tools when you have a clear use-case for dynamic behaviour, rather than static (but more readable) syntax.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This seems like such a simple question, but there don't seem to be any answers that address my particular issue, which is why the init method never actually initiates the class instance variable 'listlist'.
class PointsList():
def _init_(self):
self.listlist = [None]
def addtolist(self,item):
self.listlist.append(item)
def getlist(self):
return self.listlist
a = PointsList()
a.addtolist('Scarlet')
print a.getlist()
Running the above code gives me:
AttributeError: PointsList instance has no attribute 'listlist'
The error is traced to line 5 when the 'addtolist' method attempts to add an item to the evidently nonexistent 'listlist' instance variable.
I've checked the indentation many times but it appears to be sound. Is there something wrong with my Python installation? I am using Python v2.7.5 (haven't gotten around to 2.7.6 yet) and the Spyder IDE v2.2.0
Python special methods use two underscores at the start and end; you need to name the initializer __init__, not _init_:
class PointsList():
def __init__(self):
self.listlist = [None]
Underscore characters are usually shown connecting up forming a longer line, but there are two underscores before init, and two after.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
In python, I can do something like this:
# say.py
class Speaker:
def speak(self,word):
pass
def Do(self):
self.speak("hello")
Speaker().Do()
If I run this, it would do nothing at all. I can do this in another module:
import say
class Test(say.Speaker):
def speak(self,word):
print(word)
Test().Do()
If I run this, the original speak function in say.py is overwritten completely since I inherited it when I did:
class Test(say.Speaker)
So when I run the script, it will print the word rather than doing nothing. I want the name of the script to dynamically change file names without having to edit say.rb.
If I ran say.py and did:
Speaker().do()
nothing happens, but when I run the other py module, and have it do:
Test.Do()
it is overwritten since I inherited it, and changed the function of speak. Doing Speaker().Do() as it is does nothing, but if I do Test.Do(), it does work because of the override.
Is their a ruby equivalent for what I did in python, and if so, how would I do it?
It is very similar. Here's 'say.rb':
module Say
class Speaker
def speak(word) end
def Do() speak("Hello") end
end
end
In your other module:
require 'say'
class Test < Say::Speaker
def speak(word)
puts(word)
end
end
To demonstrate:
Test.new.Do
Of course there is. What have you tried that didn't work? Read up on inheritance in Ruby.
You'd literally need only change a few characters in that Python to get it to work in Ruby.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to coding Python and I just can't seem to understand what a Def function is! I have looked and read many tutorials on it and I still don't quite understand. Can somebody explain to me what it is, what I use it for, and give me some examples. For the examples please make them easy and understandable for a newb to Python. Thanks!
def isn't a function, it defines a function, and is one of the basic keywords in Python.
For example:
def square(number):
return number * number
print square(3)
Will display:
9
In the above code we can break it down as:
def - Tells python we are declaring a function
square - The name of our function
( - The beginning of our arguments for the function
number - The list of arguments (in this case just one)
) - The end of the list of arguments
: - A token to say the body of the function starts now
The following newline and indent then declare the intentation level for the rest of the function.
It is just as valid (although uncommon) to see:
def square(number): return number * number
In this case, as there is no indentation the entirety of the function (which in this case is just one line) runs until the end of line. This is uncommon in practise and not considered a good coding style.