here is my code.
import fileinput, random
from os import system as sys
from sys import exit
class crazy8(object):
question = raw_input("please enter a yes or no question \n")
def fortune(self, filex, current):
current = r"./"
fortunes = list(fileinput.input(filex))
sys("cd", current)
print random.choice(fortunes)
crazy8.fortune(r"./crazy8")
exit(0)
When I run the program, I enter a question (I know that the program does not care what is entered). I think I did something wrong with the class. I know it works fine when there is no class: statement, but I need the class there (after I am done, I am going to use this as a module).
After the question, I get
TypeError: unbound method fortune() must be called with crazy8 instance as first argument (got str instance instead)
(I did not add any error checking yet. I will try to add try and catch/raise for if the file ./crazy8 does not exist. Also, I am later going to add a file that will automatically sys("touch ./crazy8") (on Mac/linux) and, after I find out how to create a file on Windows, I will add that.
You need to create and instance or object of the class(same thing).
x = crazy8()
x.fortuner(r,"./crazy8")
It's also considered common practice to have your classes start with capital letters and instances with lowercase.
class Crazy8
crazy8 = Crazy8()
Hope this helps
Either you should create an instance of the class and call its method, or you should make the method static.
Please refer to:
Static methods in Python
Related
I'm a little confused by what I'm seeing in the unittest file of this Exercism exercise. These are some of the tests that are run to check the validity of my program. (You create a PhoneNumber object in the main program.)
def test_area_code(self):
number = PhoneNumber("2234567890")
self.assertEqual(number.area_code, "223")
def test_pretty_print(self):
number = PhoneNumber("2234567890")
self.assertEqual(number.pretty(), "(223) 456-7890")
def test_pretty_print_with_full_us_phone_number(self):
number = PhoneNumber("12234567890")
self.assertEqual(number.pretty(), "(223) 456-7890")
I know how to create the number attribute for my class objects, but what do number.area_code and number.pretty() mean? What makes this valid Python code? I tried just creating a value like self.number.area_code = <something here>, but that didn't work. What exactly is this called and how do I create it?
Thanks!
Edit: This is another part of the unittest file:
def test_cleans_the_number(self):
number = PhoneNumber("(223) 456-7890").number
self.assertEqual(number, "2234567890")
def test_cleans_numbers_with_dots(self):
number = PhoneNumber("223.456.7890").number
self.assertEqual(number, "2234567890")
def test_cleans_numbers_with_multiple_spaces(self):
number = PhoneNumber("223 456 7890 ").number
self.assertEqual(number, "2234567890")
Doesn't this part mean that number is an attribute? This is why I misunderstood the previously quoted section. The unittest file seems to be using number in two different ways, and I didn't catch it in the former part!
I'm new to python and I'm tring to make a class for a modul which checking curses in texts.
can someone help please?
import urllib
class Checktext:
def __init__(self, text):
self.text = text
def gettext(self):
file = open(self.text, "r")
filetext = open.read()
for word in filetext.split():
openurl = urllib.request.urlopen("http://www.wdylike.appspot.com/?q=" + word)
output = openurl.read()
truer = "true" in str(output)
print(truer)
s = Checktext(r"C:\Users\Tzach\.atom\Test\Training\readme.txt")
Checktext.gettext()
You declared s as a new Checktext object, so you need to call s.gettext() not an un-instantiated Checktext.gettext(), as that has no self to refer to
The urllib is a package. You have to import the module request that is located in the package:
import urllib.request
The open(filename) return a file object. You want to call the method of that object:
filetext = file.read()
And as G. Anderson wrote, you want to call s.gettext() instead of Checktext.gettext(). The self inside is actually equal to the s outside. If you want to be weird then you actually can use also:
Checktext.gettext(s)
Notice the s passed as your missing parameter. Here Python actually reveals how the Object Oriented things are implemented internally. In majority of OO languages, it is carefully hidden, but calling a method of an object is always internally translated as passing one more special argument that points to the instance of the class, that is the object. When defining a Python method, that special argument is explicitly named self (by convention; you can name it differently -- you can try as the lecture, but you should always keep that convention).
Thinking about it thoroughly, you can get the key idea of the hidden magic of an OO language syntax. The instance of the class (the object) is actually only a portion of memory that stores the data part, and that is passed to the functions that implement the methods. The Checktext.gettext is actually the function, the s is the object. The s.gettext() is actually only a different way to express exactly the same. AS s is the instance of the Checktext class, the fact is stored inside the s. Therefore, the s.gettext() creates the illusion that the rigth code will be called magically. It fits with the trained brain better than the function approach if the s is thought as a tangible something.
Assume that class MyClass is sometimes, but not always, defined. I have a function foo(a=None) in which argument a can be None, a string, or an object of MyClass.
My question is: If MyClass is not defined in my Python session, how can I check the type of argument a in a fashion similar to isinstance without getting a NameError?
Note on duck-typing: I am deliberately limiting the function.
I'm using Python 2.6.x and Updating is not an option. A forward-compatible solution (especially for 2.7.x) is highly appreciated.
I would suggest a different approach: polyfill the class so all code that wants to refer to it can simply do so:
try:
from foo import Bar # load the native class
except ImportError:
class Bar:
pass # implement necessary parts here
You can put this into your own module and then from mymodule import Bar everywhere it's needed. That allows all your code to use Bar regardless of whether it's defined natively or not.
Even if redefining the class isn't your preferred way to handle this, handling the ImportError is still the way to handle this situation, since you will have to import the class either way and that's where the error will occur. Instead of defining the class, you may instead want to set a class_exists = False flag or something.
If MyClass isn't defined then you have no way to reference its type.
Therefore you can have no way to verify that type(a) has the correct value.
I workarounded the problem by overriding a method in MyClass and doing nothing in it (pass). After that I no longer needed to check its type.
Different workarounds may exist for different cases. Catching the NameError could be another one.
t = 'asdfas'
print(isinstance(t, str))
try:
print(isinstance(t, MyClass))
except NameError:
print(False)
Seems to me, that such a construct may appear in future python. Like typed python, which is quite new. And in typed python we have a possibility to use future types, in apos.
So I've searched around and couldn't find an answer. I'm looking to change parameters from an object created in my main file, in a module. For example, I'm testing this with a simple piece of code here:
-this is my main file, from which i create the objects and define some properties
import class_test_2
class dog():
name=''
spots=0
def add_spots(self):
self.spots+=1
def main():
fido=dog()
fido.name='Fido'
print('Fido\'s spots: ',fido.spots)
fido.add_spots()
print('Fido\'s spots: ',fido.spots)
class_test_2.class_test()
print('Fido\'s spots: ',fido.spots)
if __name__=='__main__':
main()
-this is the module, from which I want to use functions to change the attributes in the main file
from class_test_1 import dog
def class_test():
fido.add_spots()
-So my question is how can I do this/why doesn't this piece of code above work?
Running the main function on its own shows fido's spots increasing by 1 each time its printed. Running the code calling the module however gives a NameError so my module isn't recognising the class exists even though I've managed to import it. Thanks in advance for any help.
Your variable "fido" is only defined within your "main" function. You must provide your "class_test" function with the variable.
For example:
class_test_2.class_test(fido)
Then your class_test function gets an argument. You can choose the name freely. I used the_dog in the example:
def class_test(the_dog):
the_dog.add_spots()
In this case the_dog points to the same instance of your dog class as fido.
I have the following code:
from suchandsuch import bot
class LaLaLa():
def __init__(self):
self.donenow = 0
print "LaLaLa() initialized."
return
def start(self):
pages = bot.cats_recursive('something')
for page in pages:
self.process_page(page)
When I try to run y = LaLaLa() and then y.start(), though, I get an error:
AttributeError: LaLaLa instance has no attribute 'cats_recursive'
This makes me suspect that Python is trying to call cats_recursive() not from suchandsuch's bot sub-module (as is defined at the beginning of the file), but rather from LaLaLa(), which of course doesn't have the cats_recursive() function. Is there a way to force a class instance to use an imported module, rather than just look inside itself?
Posters are correct that there is nothing wrong with the code you have posted.
It's the code you didn't post that is probably the problem. It is hinted at in your naming of cats_recursive. You haven't shown us that perhaps LaLaLa is defined in or imported into bot.py.
One way to replicate your error is:
# in suchandsuch/bot.py
class LaLaLa():
def __init__(self):
self.donenow = 0
print "LaLaLa() initialized."
# don't need a `return` here
def start(self):
pages = bot.cats_recursive('something')
for page in pages:
self.process_page(page)
bot = LaLaLa()
That's just one. Another is to have __init__.py in such and such something like:
bot = LaLaLa()
Like I said, the error is in your code structure.
print the id of the bot inside LaLaLa or captrue the error with pydb and I suspect you will see that bot is an instance of LaLaLa other than y (again check the id's)
You are doing fine. Most probably there is no cats_recursive() attribute in your module for real. Check syntax, check module content.
You might find the easiest way to do this would be to try to assign the cats_recursive() to the pages variable outside the class and then pass the variable to the start() function as a parameter. If this works then keep it that way, if it doesn't work then there's probably something wrong with the code elsewhere.