EDIT
I m trying to make a function to dynamic change the object to get acess to those classes easier.
How can i pass the "test" variable inside that object?
I'v tryied this so far.
EDIT
class Vision:
def find():
pass
class visionInstances:
visionPao = Vision(f'{PathMissionProducts}Pao.jpg')
visionLeite = Vision(f'{PathMissionProducts}Leite.jpg')
xabuska = visionInstances() #Classe
def catch_screenshot(wincap):
return wincap.get_screenshot()
def getpoints(VisionInstanceName=None, threshold=0.7):
test = VisionInstanceName
points = xabuska.visionPao.find(catch_screenshot(xabuska.wincap),threshold,"points")
points2 = xabuska.test.find(catch_screenshot(xabuska.wincap),threshold,"points")
return points2
This code returns "None"
Note on the code that "xabuska.visionPao.find" are 3 diferent objects.
I want to make the second object "test" dynamic.
points1 = is the value i want.
points2 = is the test, and return None
Related
it does not work. I want to split data as in code in lines attribute.
class movie_analyzer:
def __init__(self,s):
for c in punctuation:
import re
moviefile = open(s, encoding = "latin-1")
movielist = []
movies = moviefile.readlines()
def lines(movies):
for movie in movies:
if len(movie.strip().split("::")) == 4:
a = movie.strip().split("::")
movielist.append(a)
return(movielist)
movie = movie_analyzer("movies-modified.dat")
movie.lines
It returns that:
You can use #property decorator to be able to access the result of the method as a property. See this very simple example of how this decorator might be used:
import random
class Randomizer:
def __init__(self, lower, upper):
self.lower = lower
self.upper = upper
#property
def rand_num(self):
return random.randint(self.lower, self.upper)
Then, you can access it like so:
>>> randomizer = Randomizer(0, 10)
>>> randomizer.rand_num
5
>>> randomizer.rand_num
7
>>> randomizer.rand_num
3
Obviously, this is a useless example; however, you can take this logic and apply it to your situation.
Also, one more thing: you are not passing self to lines. You pass movies, which is unneeded because you can just access it using self.movies. However, if you want to access those variables using self you have to set (in your __init__ method):
self.movielist = []
self.movies = moviefile.readlines()
To call a function you use movie.lines() along with the argument. What you are doing is just accessing the method declaration. Also, make sure you use self as argument in method definitions and save the parameters you want your Object to have. And it is usually a good practice to keep your imports at the head of the file.
import re
class movie_analyzer:
def __init__(self,s):
for c in punctuation:
moviefile = open(s, encoding = "latin-1")
self.movielist = []
self.movies = moviefile.readlines()
#property
def lines(self):
for movie in self.movies:
if len(movie.strip().split("::")) == 4:
a = movie.strip().split("::")
self.movielist.append(a)
return self.movielist
movie = movie_analyzer("movies-modified.dat")
movie.lines()
Would like some direction on how to pull a "bucket" of data from a return object in python. The statuses is a bucket that contains a list of data to display. I've tried a few different ways and can't seem to display anything but the object reference. Basically, what's the best way to display this type of data in this "bucket" or list of data. ":type: list[ObjectedCreatedName]"
fetch = client.fetch('2Oe3UKM_Nt_NG1UG');
print(fetch.statuses)
print(type(fetch.statuses))
Output:
[<ObjectCreatedName object at 0x03CC07F0>]
<class 'list'>
class ObjectCreatedName(object):
def __init__(self):
self.code = None
self.status = None
self.count = None
You can just:
def print_sequence(sequence):
seq_type = sequence.__class__.__name__
elem_type = sequence[0].__class__.__name__ if len(sequence) > 0 else ''
print('{}[{}]'.format(seq_type, elem_type))
e.g.:
fetch = client.fetch('2Oe3UKM_Nt_NG1UG');
print_sequence(fetch.statuses)
# list[ObjectCreatedName]
I'm having trouble understanding unit testing in Python. I have an object, retailer, which creates another object, deal. deal refers to an attribute created in retailer, so I'm passing it a reference:
class deal():
def __init__(self, deal_container, parent):
The deal_container attribute also comes from retailer, which calls its own methods to create it. So how do I create everything I need to easily make a deal object?
Do I have to create an instance of retailer in my unit test and then call the method in that object that creates deal?
Can I use FactoryBoy to create an instance of retailer and how do I include the method that creates deal in that object?
What's the best way to approach this?
Here's the unit test. I'm setting up the soup_obj I need to give deal:
class TestExtractString(TestCase):
fixtures = ['deals_test_data.json']
def setUp(self):
with open('/home/danny/PycharmProjects/askarby/deals/tests/BestBuyTest.html', 'r') as myfile:
text = myfile.read().replace('\n', '')
self.soup_obj = bs4.BeautifulSoup(text,"html.parser")
self.deal = self.soup_obj.find_all('div',attrs={'class':'list-item'})[0]
def test_extracts_title(self):
z = Retailer.objects.get(pk=1)
s = dealscan.retailer(z)
d = dealscan.deal(self.deal,s)
result = d.extract_string(self.deal,'title')
and here's the relevant bit of the deal class in dealscan. There's a retailer class that creates a deal, but I haven't even written the bit in retailer that creates deal yet. I'm hoping I can mock the bits I need for deal without having to invoke retailer at all, but then how do I deal with the fact that deal references retailer?
class deal():
def __init__(self, deal_container, parent):
'''
Initializes deal object
Precondition: 0 > price
Precondition: 0 > old_price
Precondition: len(currency) = 3
:param deal_container: obj
'''
self.css = self.parent.css
self.deal_container = deal_container
self.parent = parent
self.title = self.extract_string('title')
self.currency = self.parent.currency
self.price = self.extract_price('price')
self.old_price = self.extract_price('old_price')
self.brand = self.extract_string('brand')
self.image = self.extract_image('image')
self.description = self.extract_string('description')
#define amazon category as clearance_url
#define all marketplace deals
def __str__(self):
return self.title
def extract_string(self, element, deal):
'''
:param object deal: deal object to extract title from
:param string element: element to look for in CSS
:return string result: result of string extract from CSS
'''
tag = self.css[element]['tag']
attr = self.css[element]['attr']
name = self.css[element]['name']
result = deal.find(tag, attrs={attr: name})
if result:
if element == 'title':
return result.text
elif element == 'price':
result = self.extract_price(result).text
if result:
return result
elif element == 'image':
result = self.extract_image(result)
return False
The problem is that the deal object is referencing the parent before it sets the self.parent attribute. Use:
self.parent = parent
self.css = self.parent.css
self.deal_container = deal_container
and the AttributeError goes away.
As for the question about whether it's good form to use an object to create another object in a unit test, the answer is that you can use mocks, but it's fine to do it this way. Using a helper method to set up the parent object once in setUp is acceptable and will make the code easier to read, and may improve test performance a little.
I have the following tile class which got some instance variables such as UNMAPPED,FREE etc.
Those instance variables get a default value once new instance is created, but i want to set some of this variables from a method within the instance itself.
when im trying to do so, it seems the the new value is not saved but when im doing it without any method it seems to work.
How can it be?
class tile():
def __init__(self):
self.FREE = 0
self.UNMAPPED = 1
def set_tile(self,newVal):
self.FREE = newVal
so that :
tile1 = tile()
tile1.set_tile(20) -> tile1.FREE = 0
but,
tile1.FREE = 20 -> tile1.FREE = 20
thanks for your help
I'm trying to implement trie in python. I'm using dictionaries+classes instead of lists (I know it's not optimal, but I'm just trying to make it work at all).
After debugging I found out that each layer has all letters in dictionary. I cannot understand why.
Here is my code (implementation is 100% most basic, straightforward):
class lttr:
finish = 0
pointers = {} #for letters to reference class instance
eps = lttr()
def add(word):
global eps
last = eps
for ind,x in enumerate(word):
if last.pointers.get(x,None):
last = last.pointers[x]
else:
last.pointers[x] = lttr()
last=last.pointers[x]
last.finish=1
def lookup(word):
global eps
last=eps
for ind,x in enumerate(word):
if last.pointers.get(x,None):
last=last.pointers[x]
else:
return False
return bool(last.finish)
add("pear")
print lookup("ar") #prints True ... but why?
I'm guessing you intended for each individual lttr instance to have its own unique values for finish and pointers. In which case, you need to declare them as attributes of self inside __init__, rather than just defining them at the class scope.
class lttr:
def __init__(self):
self.finish = 0
self.pointers = {} #for letters to reference class instance
Now your script will print False as expected.
Your lttr class has class variables, but you want instance variables. Class variables are unique across all instances of that class, so you only have one pointers object.
class lttr:
finish = 0
pointers = {} #for letters to reference class instance
What you want is
class lttr:
def __init__(self):
self.finish = 0
self.pointers = {}
and that works as expected.