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.
Related
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)
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 is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
For example in Python 3: print("Hello world")
And in Python 2: print "Hello world"
This makes me want to use Python 2 instead of Python 3, because it's simpler.
From http://www.python.org/dev/peps/pep-3105/
The following arguments for a print() function are distilled from a
python-3000 message by Guido himself:
print is the only application-level functionality that has a statement dedicated to it. Within Python's world, syntax is generally
used as a last resort, when something can't be done without help from
the compiler. Print doesn't qualify for such an exception.
At some point in application development one quite often feels the need to replace print output by something more sophisticated, like
logging calls or calls into some other I/O library. With a print()
function, this is a straightforward string replacement, today it is a
mess adding all those parentheses and possibly converting >>stream
style syntax.
Having special syntax for print puts up a much larger barrier for evolution, e.g. a hypothetical new printf() function is not too far
fetched when it will coexist with a print() function.
There's no easy way to convert print statements into another call if one needs a different separator, not spaces, or none at all. Also,
there's no easy way at all to conveniently print objects with some
other separator than a space.
If print() is a function, it would be much easier to replace it within one module (just def print(*args):...) or even throughout a
program (e.g. by putting a different function in builtin.print).
As it is, one can do this by writing a class with a write() method and
assigning that to sys.stdout -- that's not bad, but definitely a much
larger conceptual leap, and it works at a different level than print.
In Python2, print is a statement but in Python3, print is a function
Try this
print(print("Welcome"))
in python 2, it will produce SyntaxError: invalid syntax but in python3 it will produce
Welcome
None
It means that, first the inner print is invoked which prints Welcome and it returns None to the outer print which simply prints it.
Short simple answer: print was made a function in Python 3 as #kojiro suggested.
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
How can I call a python function from another file?
I read
how to call a function from another file?
And following what is suggested, but I think it does not work for me because
both myscript.py and myaotherscript.py uses variables likes 'argv', 'args'
I want to call in myscript.py
def main(argv):
myanotherscript.main(argv)
The following works for me:
File1.py:
import file2
import sys
def main(argv):
file2.main(argv)
if __name__ == "__main__":
main(sys.argv)
File2.py:
def main(argv):
# do something useful...
Just pass the argv (and possible argc) to your other script's main method.
If the input from myscript.py's main is something that would be accepted by myanotherscript.py's main method, this would be fine.
However, you should be asking yourself if this is what you really need. Alternatively you could simply construct another list of arguments to pass. The argument names only have method scope so you can reuse names across methods (so long as you don't declare them as globals).