Python 3 : Getter is not returning the data it should be - python-3.x

I have a parent Class that has a setter that returns queryFiltre value and a getter that is supposed to pass the queryFiltre value to my child Class. queryFiltre Should return an SQL query like "SELECT * FROM Report WHERE GA_RPM > 0 and CAMPAIGN LIKE '%TT%'... ".
The print() in the setter returns a SQL query, but the print() of the getter when called in the child Class returns something like " <main.SimpleGrid object at 0x042AF2B0>".
What's wrong with my code? Please bear with me as I'm still learning and oop is still an abstract concept in my head.
I've added comments in the code so you can see what happens where:
class SimpleGrid(gridlib.Grid): ##, mixins.GridAutoEditMixin):
def __init__(self, parent, log):
gridlib.Grid.__init__(self, parent, -1)
########### DATABASE CONNECT
self.path =os.path.dirname(os.path.realpath(__file__))
self.dbfile = os.path.join(self.path , "report.db")
self.db_conn = sqlite3.connect(self.dbfile)
self.theCursor = self.db_conn.cursor()
########### SETTING FILE CONNECT
self.configFile = os.path.join(self.path , "config.ini")
self.config = configparser.ConfigParser()
self.config.read(self.configFile)
########### Calling th Getter and Setter
self.queryFiltre = self.setQueryFiltre(self)
self.getQueryFiltre()
########### Setter
def setQueryFiltre(self,queryFiltre):
if self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "true":
network = ""
elif self.config.get('Network', 'taboola') == "true" and self.config.get('Network', 'ob') == "false":
network = " and CAMPAIGN LIKE '%TB%'"
elif self.config.get('Network', 'outbrain') == "true" and self.config.get('Network', 'tb') == "false":
network = " and CAMPAIGN LIKE '%OB%'"
else:
network = ""
queryFiltre = "SELECT * FROM Report WHERE GA_RPM > 0 " + network + " and STATUS = '1' ORDER BY CLICKS DESC"
########### The print below returns the right value of queryFiltre
print(queryFiltre)
return queryFiltre
########### Getter
def getQueryFiltre(queryFiltre):
queryFiltre = queryFiltre
return queryFiltre
class TestFrame(wx.Frame):
def __init__(self, parent, log):
wx.Frame.__init__(self, parent, 0, "Native Ads Reports V1.0", size=(1400,800))
self.grid = SimpleGrid(self, log)
########### Calling the Getter of the parent Class
self.queryFiltre = self.grid.getQueryFiltre()
########### DATABASE CONNECT
self.path =os.path.dirname(os.path.realpath(__file__))
self.dbfile = os.path.join(self.path , "report.db")
self.db_conn = sqlite3.connect(self.dbfile)
self.theCursor = self.db_conn.cursor()
########### The print below returns a bad value, something like : <__main__.SimpleGrid object at 0x042AF2B0>
print(self.queryFiltre)
You'll notice also that I've added the script to define the path and to connect to the db in both classes, is there a way to do it only once in the first Class?
Thank you,

Your getQueryFiltre() in SimpleGrid has the wrong indentation, and is missing the first argument self. The way you've written it, it is a function within the scope of your setQueryFiltre(), and it isn't called from anywhere.
It should be indented to the same level as setQueryFiltre, and have a first argument self.
By the way, you shouldn't be using getters. It's not pythonic, as explained here: https://stackoverflow.com/a/36943813/11451509

Related

How do I test for str equality using factory_boy faker method?

I have two factory classes, the other is linked to the one through foreign key relationships, and was kinda hoping to achieve some similarities with the attributes. To start with, the model looks something like this:
class Track(models.Model):
response = models.ForeignKey('Response')
def __str__(self):
return str(self.response)
class Response(models.Model):
title = models.CharField(max_length=640)
def __str__(self):
return self.title
I should be able to access these classes as I have done below
r = Response(title='foo')
r.save()
t = Track(response=r)
t.save()
# with this I wanted to test that str(t) == t.response
The factory classes look like this:
class ResponseFactory(factory.django.DjangoModelFactory):
class Meta:
model = Response
title = factory.Faker('text')
class TrackFactory(factory.django.DjangoModelFactory):
class Meta:
model = Track
response = factory.SubFactory(ResponseFactory)
Below is how I have accessed these factory classes to test for str equality
track = TrackFactory() # generates random string e.g `foo`
a = str(track) # == foo
b = track.response # == foo
# however I get an assertion error with the statement below
assert a == b
Could you point out where I've gone wrong, thank you.

How to print class variables in a list

So I am very new to coding and started with python, I am trying to build a class in a program that puts together a DnD party by randomising their attributes. So far I can get the program to initialise instances of the party members and just give the user a prompt on how many of the hero's to choose from they would like in their party. My issue is that after setting the lists up and getting everything in place. I am unable to print any of the attributes of the individual heros. Regardless of whether I am calling them from within the lists or if I am directly trying to print them. I have tried using __str__ to create strings of the attributes but I am clearly missing something. Any help would be greatly appreciated.
import random
class Party:
def __init__(self, name="", race="", alignment="", class_=""):
self.name = name
while name == "":
name = random.choice(names)
# print(name)
self.race = race
while race == "":
race = random.choice(races)
# print(race)
self.alignment = alignment
while alignment == "":
alignment = random.choice(alignments)
# print(alignment)
self.class_ = class_
while class_ == "":
class_ = random.choice(classes)
# print(class_)
def character_stats(self):
return "{} - {} - {} - {}".format(self.name, self.race, self.class_, self.alignment)
Each attribute pulls a random value from a list. My format statement is the latest attempt to get the values of the attributes to print rather than the object/attributes instead.
I apologise if any of the terminology is wrong, very very new to this
You are not assigning anything else but the input, (in this case being an empty string "" to the attribuytes. In your minimal example you have this constructor:
class Party:
def __init__(self, name=""):
self.name = name
while name == "":
name = random.choice(names)
After you randomly assign a new name from names, you should assign it to self, otherwise the local variable just goes out of scope when the __init__ method finishes. This code snippet should work:
class Party:
def __init__(self, name=""):
while name == "":
name = random.choice(names)
# Now we assign the local variable as
# an attribute
self.name = name

sub-classing a peewee field type to add behavior

I am trying to add the required behavior to a CharFiled or TextField so I can store a list of lists and retrieve it as a list of lists again. I am not asking for a solution rather I would like to see an example where a subclassing of an already supported field type is done as I didn't find any in the documentation or the Internet.
Do I have to do it as explained in the documents for creating a custom type?
for example:
class mylistoflists(TextField):
if yes, then what do I have to assign to field_type?
Example code (see tests/fields.py for full example):
class ListField(TextField):
def db_value(self, value):
return ','.join(value) if value else ''
def python_value(self, value):
return value.split(',') if value else []
class Todo(TestModel):
content = TextField()
tags = ListField()
class TestCustomField(ModelTestCase):
requires = [Todo]
def test_custom_field(self):
t1 = Todo.create(content='t1', tags=['t1-a', 't1-b'])
t2 = Todo.create(content='t2', tags=[])
t1_db = Todo.get(Todo.id == t1.id)
self.assertEqual(t1_db.tags, ['t1-a', 't1-b'])
t2_db = Todo.get(Todo.id == t2.id)
self.assertEqual(t2_db.tags, [])
t1_db = Todo.get(Todo.tags == Value(['t1-a', 't1-b'], unpack=False))
self.assertEqual(t1_db.id, t1.id)

Trigger a function when any property of an object changes with RxPy

In RxPy, is there anything similar to INotifyPropertyChanged in .NET framework mentioned here? I'm trying to add an observer to an object, so that any property of the object changes, a function will be called.
Try something like this:
class A(object):
def __init__(self):
self._my_attr = None
self.property_changed = Subject()
...
#property
def my_attr(self):
return self._my_attr
#my_attr.setter
def my_attr(self, value):
if value != self._my_attr:
self._my_attr = value
self.property_changed.on_next(('my_attr', value))
a = A()
a.property_changed.subscribe(print)
a.my_attr = 1
a.my_attr = 3

Help me to better understand CherryPy PageHandlers

Let's say I have some code (using CherryPy) that looks like this:
import cherrypy
class Names:
def index(self, name=None):
return "Names.index: " + str(name)
index.exposed = True
class Root:
def index(self):
return "This is the root"
index.exposed = True
if __name__ == "__main__":
root = Root()
root.names = Names()
cherrypy.tree.mount(root, '/')
cherrypy.engine.start()
cherrypy.engine.block()
If I hit the url http://localhost:8080/names/, I see Names.index: None, which is fine. That means the Names() class is being called.
But, if I go to http://localhost:8080/names/mark, I get a 404 Error instead of the Names.index: mark I was expecting.
This confuses me because, according to the PageHandler documentation:
When a request is processed, the URI is split into its components, and each one is matched in order against the nodes in the tree. Any trailing components are "virtual path" components and are passed as positional arguments.
Now let's say I change the Names() class to look like this:
class Names:
def index(self, name=None):
return "Names.index: " + str(name)
index.exposed = True
def name(self, name=None):
return "Names.name: " + str(name)
name.exposed = True
Now I can go to http://localhost:8080/names/name/mark and I see Names.name: mark.
Can someone explain what's happening here?
The index method is an exception to the partial matching rules. You can use the default method instead, or in this particular example make names a method itself.

Resources