I'm trying to initiate a property inside a class but it doesn't seem to work.
The class should use another class. this is the code I've made:
Book.py:
from Paragraph import Paragraph as Paragraph
'''definitions'''
class Book:
def __init__(self, book):
self._paragraphs = book
'''paragraphs property'''
#property
def paragraphs(self):
return self._paragraphs
#paragraphs.setter
def paragraphs(self, book):
paragraph_0 = Paragraph(book[0x0:0x100])
paragraph_1 = Paragraph(book[0x200:0x300])
paragraph_2 = Paragraph(book[0x300:0x400])
paragraph_3 = Paragraph(book[0x400:0x500])
self._paragraphs = [paragraph_0, paragraph_1, paragraph_2, paragraph_3]
Paragraph.py:
'''definitions'''
class Paragraph:
def __init__(self, paragraph):
self._paragraph = paragraph
self._first_section = paragraph[0x0:0x10]
self._second_section = paragraph[0x10:0x100]
'''paragraph property'''
#property
def paragraph(self):
return self._paragraph
#paragraph.setter
def paragraph(self, paragraph):
self._paragraph = paragraph
'''first_section property'''
#property
def first_section(self):
return self._first_section
#first_section.setter
def first_section(self, first_section):
self._first_section = first_section
'''second_section property'''
#property
def second_section(self):
return self._second_section
#second_section.setter
def second_section(self, second_section):
self._second_section = second_section
Then I create a Book instance:
first_book = Book(some_hex_list)
And I expect to have 4 paragraphs in first_book._paragraphs and each paragraph should have a first and a second section property (as in the Paragraph class). Instead first_book._paragraphs just contains the original some_hex_list data.
I'd like to create a Book instance and initiate it so in the end I should get something like this:
first_book
-->_paragraphs
----->paragraph_0
---------->_first_section
---------->_second_section
----->paragraph_1
---------->_first_section
---------->_second_section
----->paragraph_2
---------->_first_section
---------->_second_section
----->paragraph_3
---------->_first_section
---------->_second_section
Thanks!
Related
Given this example code where we have a series of log processors, I can't help feeling there ought to be a more pythonic/efficient way of deciding which log processor to use to process some data:
class Component1ErrorLogProcessor:
def process(logToProcess):
# Do something with the logs
pass
class Component2ErrorLogProcessor:
def process(logToProcess):
# Do something with the logs
pass
class LogProcessor:
def __init__(self):
self.component1 = Component1ErrorLogProcessor()
self.component2 = Component2ErrorLogProcessor()
def process_line(self, line, component):
if component == "Component1Log-" or component == "[Component1]":
self.component1.process_errors(line)
elif component == "Component2Log-" or component == "[Component2]":
self.component2.process_errors(line)
I'd personally use the idea of registry, so you map each class to component names.
There are a bunch of different ways to go about this, here's a quick example by using a base class:
class ComponentLogProcessor(object):
_Mapping = {}
#classmethod
def register(cls, *component_names):
for name in component_names:
cls._Mapping[name] = cls
#classmethod
def cls_from_component(cls, component):
return cls._Mapping[component]
class Component1ErrorLogProcessor(ComponentLogProcessor):
def process(logToProcess):
# Do something with the logs
pass
Component1ErrorLogProcessor.register('Component1Log-', '[Component1]')
class Component2ErrorLogProcessor(ComponentLogProcessor):
def process(logToProcess):
# Do something with the logs
pass
Component2ErrorLogProcessor.register('Component2Log-', '[Component2]')
class LogProcessor:
def process_line(self, line, component):
ComponentLogProcessor.cls_from_component(component).process_errors(line)
In python, which is better:
class MyAPI:
def __init__(self):
self.dao = MyDAO()
def getsomething(self):
something = self.dao.grabSomething()
newsomething = operateon(something)
return newsomething
def getsomethingelse()
somethingelse = self.dao.grabSomethingElse()
newsomethingelse = operateon(somethingelse)
return newsomethingelse
OR
class MyAPI:
def getsomething(self):
dao = MyDAO()
something = dao.grabSomething()
newsomething = operateon(something)
return newsomething
def getsomethingelse()
dao = MyDAO()
somethingelse = dao.grabSomethingElse()
newsomethingelse = operateon(somethingelse)
return newsomethingelse
I am a complete python noob coming from a java spring background and I am really trying to understand the difference here.
I am creating a Flask Website and i want to display different logout links based your current page i.e
If we’re on the home page and logged in, have this link be wrapped in h2 tags
If we’re on a different page and logged in, have this link be wrapped in underline tags
If we’re logged in, have this link wrapped in strong tags
So far i have tried upto here.
class HtmlLinks():
html =""
def set_html(self, html):
self.html = html
def get_html(self):
return self.html
def render(self):
print(self.html)
class LogoutLink(HtmlLinks):
def __init__(self):
self.html = "Logout"
class LogoutLinkH2Decorator(HtmlLinks):
def __init__(self, logout_link):
self.logout_link = logout_link
self.set_html("<h2> {0} </h2>").format(self.logout_link.get_html())
def call(self, name, args):
self.logout_link.name(args[0])
class LogoutLinkUnderlineDecorator(HtmlLinks):
def __init__(self, logout_link):
self.logout_link = logout_link
self.set_html("<u> {0} </u>").format(self.logout_link.get_html())
def call(self, name, args):
self.logout_link.name(args[0])
class LogoutLinkStrongDecorator(HtmlLinks):
def __init__(self, logout_link):
self.logout_link = logout_link
self.set_html("<strong> {0} </strong>").format(self.logout_link.get_html())
def call(self, name, args):
self.logout_link.name(args[0])
logout_link = LogoutLink()
is_logged_in = 0
in_home_page = 0
if is_logged_in:
logout_link = LogoutLinkStrongDecorator(logout_link)
if in_home_page:
logout_link = LogoutLinkH2Decorator(logout_link)
else:
logout_link = LogoutLinkUnderlineDecorator(logout_link)
logout_link.render()
I am getting Attribute error
AttributeError: 'NoneType' object has no attribute 'format'
What wrong i am doing and how to rectify it. Please Help.
So you have a few lines that looks like this:
self.set_html("<h2> {0} </h2>").format(self.logout_link.get_html())
You probably want them to look like:
self.set_html("<h2> {0} </h2>".format(self.logout_link.get_html()))
set_html returns nothing, but you try to call for format method on its returned value.
self.set_html("<strong> {0} </strong>").format(self.logout_link.get_html())
for some reason when I try to add an object to a dictionary in a class, where the dictionary belongs to another class and objects are added/removed by class functions it always seems to fail adding.
Heres the datahandler :
class datastore():
def __init__(self, dict=None):
self.objectStore = {}
self.stringStore = {}
if dict is not None:
self.objectStore = dict
def __addobj__(self,obj,name):
print("adddedval")
self.objectStore[name] = obj
def __getobject__(self,name):
_data = self.objectStore.get(name)
return _data
def __ripobj__(self,name,append):
if isinstance(append, object):
self.objectStore[name] = append
def __returnstore__(self):
return self.objectStore
def __lst__(self):
return self.objectStore.items()
and heres the trigger code to try to add the item :
if self.cmd=="addtkinstance-dev":
print("Adding a tk.Tk() instance to dataStore")
#$$ below broken $$#
_get = datastore.__dict__["__returnstore__"](self.dat)
_get["test-obj"] = tk.Tk()
datastore.__init__(self.dat, dict=_get)
#--------------------------------------------#
tool(tk.Tk(), "test-obj", datastore())
and also heres the init for the class that trys to add the object
class cmdproc(tk.Tk, datastore):
def __init__(self,lst,variable_mem,restable):
self.pinst = stutils(lst,restable,variable_mem)
self.vinst = varutils(variable_mem,lst,restable)
self.tki = tkhandler()
self.dat = datastore(dict=None)
datastore.__init__(self, dict=datastore.__returnstore__(self.dat))
tk.Tk.__init__(self)
self.lst = lst
self.vdat = variable_mem
self.restable = restable
please help this is seriously baffling me
(note that tkhandler dosn't have to do with anything)
I'm not sure if this is effective or not. It works, but sometimes i feel...weird about it. Can you please tell me if this is a good way or not?
I threw the code on pastebin, because i think it's a bit too much to put here: http://pastebin.com/662TiQLq
EDIT
I edited the title to make it more objective.
I'm just guessing that the questioner is asking about creating a dictionary of functions in the __ init __ function of the handlers, and then using this dict in the "get" function to look up specific functions. If this is the question, then IMHO a clearer approach would be to set up separate handlers for each different function. For example
class QuotesView(webapp.RequestHandler):
"""Super class for quotes that can accommodate common functionality"""
pass
class QuotesViewSingle(QuotesView):
def get(self):
...
class QuotesViewRandom(QuotesView):
def get(self):
...
class QuotesViewAll(QuotesView):
def get(self):
...
def main():
application = webapp.WSGIApplication([('/quote/new',NewQuote),
(r'/quotes/single',QuotesViewSingle),
(r'/quotes/all',QuotesViewAll),
(r'/quotes/random',QuotesViewRandom),
...
('/', MainHandler)],
debug=True)
BTW. A lot of people use the regex in the WSGIApplication calls to parse out arguments for the get functions. There's nothing particularly wrong with it. I'm not a big fan of that feature, and prefer to parse the arguments in the get functions. But that's just me.
For completeness here's the original code:
class Quote(db.Model):
author = db.StringProperty()
string = db.StringProperty()
class MainHandler(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
quotes = Quote.all()
path = os.path.join(os.path.dirname(__file__),'quotery.html')
template_values = {'quotes':quotes,'user':user,'login_url':users.create_login_url('/')}
self.response.out.write(template.render(path, template_values))
class QuoteHandler(webapp.RequestHandler):
def __init__(self):
self.actions = {'fetch':self.fetch, 'random':self.fetch_random}
#Memcache the number of quotes in the datastore, to minimize datastore calls
self.quote_count = memcache.get('quote_count')
if not self.quote_count:
self.quote_count = self.cache_quote_count()
def cache_quote_count(self):
count = Quote.all().count()
memcache.add(key='quote_count', value=count, time=3600)
return count
def get(self, key):
if key in self.actions:
action = self.actions[key]
action()
def fetch(self):
for quote in Quote.all():
print 'Quote!'
print 'Author: ',quote.author
print 'String: ',quote.string
print
def fetch_random(self):
max_offset = self.quote_count-1
random_offset = random.randint(0,max_offset)
'''self.response.out.write(max_offset)
self.response.out.write('\n<br/>')
self.response.out.write(random_offset)'''
try:
query = db.GqlQuery("SELECT * FROM Quote")
quotes = query.fetch(1,random_offset)
return quotes
'''for quote in quotes:
self.response.out.write(quote.author)
self.response.out.write('\n')
self.response.out.write(quote.string)'''
except BaseException:
raise
class NewQuote(webapp.RequestHandler):
def post(self):
author = self.request.get('quote_author')
string = self.request.get('quote_string')
if not author or not string:
return False
quote = Quote()
quote.author = author
quote.string = string
quote.put()
QuoteHandler().cache_quote_count()
self.redirect("/")
#return True
class QuotesView(webapp.RequestHandler):
def __init__(self):
self.actions = {'all':self.view_all,'random':self.view_random,'get':self.view_single}
def get(self, key):
if not key or key not in self.actions:
self.view_all()
if key in self.actions:
action = self.actions[key]
action()
def view_all(self):
print 'view all'
def view_random(self):
quotes = QuoteHandler().fetch_random()
template_data = {}
for quote in quotes:
template_data['quote'] = quote
template_path = os.path.join(os.path.dirname(__file__),'base_view.html')
self.response.out.write(template.render(template_path, template_data))
def view_single(self):
print 'view single'
def main():
application = webapp.WSGIApplication([('/quote/new',NewQuote),(r'/quotes/(.*)',QuotesView),(r'/quote/(.*)',QuoteHandler),('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)