I made first folder for Class Movie:
import webbrowser
class Movie():
def __init__(self,movie_title,movie_storyline,poster_image,trailer_youtube):
self.title=movie_title
self.storyline=movie_storyline
self.poster_image_url=poster_image
self.trailer=trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer)
Then in another file, I am trying to call the function:
import media
toy_story= media.Movie("toy_story","a boy who have toys","http://www.imdb.com/title/tt0114709/mediaviewer/rm3813007616","http://www.imdb.com/videoplayer/vi2052129305?playlistId=tt0114709&ref_=tt_ov_vi")
avatar=media.Movie("Avatar","A marine on an alien planet","http://www.imdb.com/title/tt0499549/mediaviewer/rm843615744","http://www.imdb.com/title/tt0499549/videoplayer/vi531039513?ref_=tt_ov_vi")
avatar.show_trailer()
But, I am getting below error:
AttributeError: Movie instance has no attribute 'show_trailer'
Any suggesions?
I think your indentation is wrong for your class Movie. I cant reproduce the problem with the following 2 files in the same folder - perhaps your method is not correctly indented to be part of the class:
media.py
import webbrowser
class Movie():
def __init__(self,movie_title,movie_storyline,poster_image,trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer = trailer_youtube
def show_trailer(self):
print(self.trailer)
test.py
import media
toy_story=media.Movie("toy_story",
"a boy who have toys",
"http://www.imdb.com/title/tt0114709/mediaviewer/rm3813007616",
"http://www.imdb.com/videoplayer/vi2052129305?playlistId=tt0114709&ref_=tt_ov_vi")
avatar=media.Movie("Avatar",
"A marine on an alien planet",
"http://www.imdb.com/title/tt0499549/mediaviewer/rm843615744",
"http://www.imdb.com/title/tt0499549/videoplayer/vi531039513?ref_=tt_ov_vi")
avatar.show_trailer()
Output:
>> http://www.imdb.com/title/tt0499549/videoplayer/vi531039513?ref_=tt_ov_vi
>> Process finished with exit code 0
Related
In line 81, I get an error: 'str' object has no attribute 'getCode'
but then I don't understand why lines 80-83 work fine.
I need to implement reading and writing an xml file.
The deliveries class has 2 fields of other classes (parts and providers).
I don't understand how to make a mistake, please give me a hint.
import os,xml.dom.minidom
from data import data
class dataxml(data):
def read(self):
dom=xml.dom.minidom.parse(self.getInp())
dom.normalize()
for node in dom.childNodes[0].childNodes:
if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='providers'):
code,provider,title,adres,telephone=0,"","","",""
for t in node.attributes.items():
if t[0]=="code":code=int(t[1])
if t[0]=="provider":provider=t[1]
if t[0]=="title":title=t[1]
if t[0]=="adres":adres=t[1]
if t[0]=="telephone":telephone=t[1]
self.getLib().createProviders(code,provider,title,adres,telephone)
if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='parts'):
code,title,articule,price,note=0,"",0,0,""
for t in node.attributes.items():
if t[0]=="code":code=int(t[1])
if t[0]=="title":title=t[1]
if t[0]=="articule":articule=int(t[1])
if t[0]=="price":price=int(t[1])
if t[0]=="note":note=t[1]
self.getLib().createParts(code, title, articule, price, note)
if (node.nodeType==node.ELEMENT_NODE)and(node.nodeName=='deliveries'):
code,providers,parts,guantity,date=0,None,None,0,""
for t in node.attributes.items():
if t[0]=="code":code=int(t[1])
if t[0]=="guantity":guantity=int(t[1])
if t[0]=="providers":
providers=self.getLib().getProviders(int(t[1]))
if t[0]=="parts":
parts=self.getLib().getParts(int(t[1]))
if t[0]=="date":date=t[1]
self.getLib().createDeliveries(code,providers,parts,guantity,date)
def write(self):
dom=xml.dom.minidom.Document()
root=dom.createElement("shop")
dom.appendChild(root)
for a in self.getLib().getProvidersList():
pro=dom.createElement("providers")
pro.setAttribute('code',str(a.getCode()))
pro.setAttribute('provider',a.getProvider())
pro.setAttribute('title',a.getTitle())
pro.setAttribute('adres',a.getAdres())
pro.setAttribute('telephone',a.getTelephone())
root.appendChild(pro)
for p in self.getLib().getPartsList():
par=dom.createElement("parts")
par.setAttribute('code',str(p.getCode()))
par.setAttribute('title',p.getTitle())
par.setAttribute('articule',str(p.getArticule()))
par.setAttribute('price',str(p.getPrice()))
par.setAttribute('note',p.getNote())
root.appendChild(par)
for b in self.getLib().getDeliveriesList():
de=dom.createElement("deliveries")
de.setAttribute('code',str(b.getCode()))
de.setAttribute('guantity',str(b.getGuantity()))
de.setAttribute('date',b.getDate())
if b.getProviders():
pc=b.getProviders().getCode()
else:pc=""
de.setAttribute('providers',str(pc))
if b.getParts():
ppc=b.getParts().getCode() #'str' object has no attribute 'getCode'
else:ppc=""
de.setAttribute('parts',str(ppc))
root.appendChild(de)
f = open(self.getOut(),"w")
#f.write(dom.toprettyxml(encoding='utf-8'))
f.write(dom.toprettyxml())
I tried to do this, but there were only more mistakes.
for b in self.getLib().getDeliveriesList():
de=dom.createElement("deliveries")
de.setAttribute('code',str(b.getCode()))
de.setAttribute('guantity',str(b.getGuantity()))
de.setAttribute('date',b.getDate())
de.setAttribute('providers',b.getProviders()) #
de.setAttribute('parts',b.getParts()) #
I put the functions from the following program into a module but when I import the module into a separate program and call the functions I get an error (see below). What do I need to do for the functions to run correctly using the module? Any help is much appreciated.
Original Program:
def print_m(unprinted, completed):
while unprinted:
current = unprinted.pop()
print("Printing: " + current)
completed.append(current)
def show_completed(completed):
print("\nThe following have been printed:")
for completed_item in completed:
print(completed_item)
unprinted = ['star', 'sword', 'model']
completed = []
print_m(unprinted, completed)
show_completed(completed)
Putting the functions in a module - printing_functions.py:
def print_m(unprinted, completed):
while unprinted:
current = unprinted.pop()
print("Printing: " + current)
completed.append(current)
def show_completed(completed):
print("\nThe following have been printed:")
for completed_item in completed:
print(completed_item)
Wrote separate program to import the module:
import printing_functions as pf
unprinted = ['star', 'sword', 'model']
completed = []
pf.print_m(unprinted, completed)
pf.show_completed(completed)
When I run the program I get the following error:
NameError: name 'completed' is not defined
UPDATE:
I used shorter terms in the code above and it DOES appear to work, which makes me more baffled. Posting the original code below. If the above works, why doesn't the module below work?
def print_models(unprinted_designs, completed_designs):
"""
Simulate printing each design, until none are left.
Move each design to completed_models after printing.
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
#Simulate creating a 3D print from the design.
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
Module
def print_models(unprinted_designs, completed_designs):
"""
Simulate printing each design, until none are left.
Move each design to completed_models after printing.
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
#Simulate creating a 3D print from the design.
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
New Program
import printing_functions as pf
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
pf.print_models(unprinted_designs, completed_models)
pf.show_completed_models(completed_models)
Traceback:
Traceback (most recent call last):
File "/home/pi/Documents/Python Projects/python_work/8-15_printing_models.py", line 6, in
pf.print_models(unprinted_designs, completed_models)
File "/home/pi/Documents/Python Projects/python_work/printing_functions.py", line 11, in print_models
completed_models.append(current_design)
NameError: name 'completed_models' is not defined
Hi when I tried to use this piece of code:
import media
toy_story = media.Movie("Toy Story","A story of a boy and his toys come to life","http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg","https://www,youtube.com/watch?v=vwyZH85NQC4")
print(toy_story.storyline)
The directory for media and this file is: C:\Users\Lukes\Desktop\media
The code for media is here:
class Movie():
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
and whenever I try to run entertainment_center.py
it comes out with this:
Traceback (most recent call last):
File "C:/Users/Lukes/Desktop/media/entertainment_center.py", line 1, in <module>
import media
File "C:/Users/Lukes/Desktop/media\media.py", line 2
^
IndentationError: expected an indented block
The method __init__ is with the class scope. Indent it to consider that.
class Movie(object):
def __init__( self ):
self.id = 0
Plus, don't indent the top import instruction in the first file.
I have two Scripts. Script 1 is titled schemeDetails.The second script is a test script called temporaryFile that creates a schemeSetup object using the schemeSetup class which is within schemeDetails. Everything is hunky dory up to the point where I try to acess the method insertScheme which is within the schemeSetup Class.
I have imported the schemeDetails script using the following:
import schemeDetails
reload(schemeDetails)
from schemeDetails import *
I can create the schemeDetails Object and access its attributes
d = schemeDetails.schemeSetup() -- fine
print(d.scheme) -- fine
d.insertScheme() -- throws error
but trying to call the insertScheme function throws an error
I don't know why this is happening as the import statement looks above board to me. Any advice appreciated
from sikuli import *
import os
class schemeSetup(object):
#Uses default values
def __init__(
self,
scheme = "GM",
cardNumber = "1234567A",
month = "December",
year = "2015",
setSchemeAsDefault = True):
#Provide default values for parameters
self.scheme = scheme
self.cardNumber = cardNumber
self.month = month
self.year = year
self.setSchemeAsDefault = setSchemeAsDefault
#schemeDetails is not a sub
# class of patient. It is simply defined within the patient class
# - there is a huge difference.
#====================================================#
#schemeDetails Function
def insertScheme(self):
print("insertScheme Works")
#r = Regions()
#r.description("Patient Maintenance", "schemeDetails")
#myRegion = r.createRegion()
#myRegion.highlight(1)
#click(myRegion.find(insertSchemeButton))
#click(myRegion.find(blankSchemeEntry))
#type(self.scheme + Key.ENTER + Key.ENTER)
#type(self.cardNumber + Key.ENTER)
#type(self.month + Key.ENTER)
#type(self.year + Key.ENTER)
#type(" ")
#unticks HT link, HT linking should be in a separate function
#====================================================#
#schemeDetails Function
def editScheme(self):
print("editScheme Works")
#====================================================#
def deleteScheme(self):
pass
#====================================================#
It may be of importance that calling either of the bottom functions does not produce an error. If I put print("Hello") under editScheme, and call that method using s.editScheme the program compiles but I get no output. If I run print(s.editScheme) it returns None
Well it seems to be fixed now after changing the import format to this
import schemeDetails
from schemeDetails import schemeSetup
s = schemeDetails.schemeSetup()
I've been working on a tiled map renderer, and I've tried to make a seperate Class in another file. I get this error message:
Type Error: 'renderer' object is not callable
Here's the render.py file:
import pyglet, json
from pyglet.window import key
from pyglet.gl import *
from ConfigParser import SafeConfigParser
from cocos.layer import *
from cocos.batch import *
from cocos.sprite import Sprite
class renderer( Layer ):
def __init__(self, mapname):
super( renderer, self ).__init__()
parser = SafeConfigParser()
try:
world = parser.read('maps/'+mapname+'.txt')
print world
except IOError:
print("No world file!")
return
layer = json.loads(parser.get('layer1', 'map'))
tiletype = parser.get('type', 'tile')
print tiletype
tilesize = 64
for x in range(0, len(layer)):
for y in range(0, len(layer[x])):
self.spr = Sprite("image/tiles/"+tiletype+"/"+str(layer[x][y])+".png")
self.spr.position = ((x+1)*tilesize, (y+1)*tilesize)
self.add(self.spr)
And this is the piece of code I call it with:
from other.render import renderer
world = renderer('buildnew')
world()
File Structure:
game/main.py
game/other/render.py
What am I doing wrong?
world = renderer('buildnew')
world()
First you make an instance of the renderer class and store it to world.
But then you write world(), which is wrong cause this object is not callable.
If you want to make world a callable object, you should implement the __call__ method in the renderer class.