trend.py and test_trend.py are in the same folder. I have a class Trend with a function find_regres_values that is called from a instance method perform_analysis.
trend.py:
class Trend:
def __init__(self, values, trend_type):
self.all_values = values
def permorn_analysis(self, first, trend_type):
#blabla
vals_reg = ["a", "b", "c", "d"]
find_regres_values(vals_reg, first, trend_type)
def find_regres_values(vals_reg, first, trend_type):
#do somethin
pass
in test_trend.py
from trend import find_regres_values
class ConsecRegions(unittest.TestCase):
def test_find_regres_values_decreas_min_before_max(self):
#initialize some values
output = find_regres_values(vals_reg, first, trend_type)
self.assertEqual(output, result)
It shows me an error:
File "test_trend.py", line 2, in <module>
from trend import find_regres_values
ImportError: cannot import name find_regres_values
How do I import one function for testing?
find_regres_values is a method of the class Trend, If you want find_regres_values to be its own function then remove the indentation
class Trend:
def __init__(self, values, trend_type):
self.all_values = values
def permorn_analysis(self,first,trend_type)
#blabla
vals_reg = some list
find_regres_values(vals_reg, first, trend_type)
def find_regres_values(vals_reg, first, trend_type):
#do something
What Python version you use?
If Python 3.x:
Create empty file __init__.py
For correct import use this code:
from trend import Trend
and edit call of method:
from trend import Trend
class ConsecRegions(unittest.TestCase):
def test_find_regres_values_decreas_min_before_max(self):
#initialize some values
output = Trend.find_regres_values(vals_reg, first, trend_type)
self.assertEqual(output, result)
For information:
In file trend.py after permorn_analysis method insert a colon.
Related
I am trying to create 2 python classes, class CsvtoDataFrame for moving data from csv to DataFrame. and class DataFrametoDB from Dataframe to database. When I am trying to return the dataframe from CsvtoDataFrame and print it. It says "<main.CsvtoDataFrame object at 0x00981890>" How can I see the data of the dataframe outside the CsvtoDataFrame . I need help in this. Please!
import pandas as pd
class CsvtoDataFrame:
global pd_sales
def init(self,FileName):
self.FileName = FileName
pd_sales=pd.read_csv(FileName)
#print(pd_sales)
def ReturnFile(self):
return pd_sales
class DataFrametoDB:
def init(self,obj):
self.pd_sales=obj.pd_sales
print(self.pd_sales)
df=CsvtoDataFrame('test.csv')
print(df)enter image description here
In order to return pd_sales, you may need to create another function, insteading of doing in def init(self, FileName).
import pandas as pd
class CsvtoDataFrame:
global pd_sales
def __init__(self,File):
self.FileName = File
#print(pd_sales)
def readcvs(self):
pd_sales=pd.read_csv(self.FileName)
return pd_sales;
class DataFrametoDB:
def __init__(self,obj):
self.pd_sales=obj.pd_sales
print(self.pd_sales)
df=CsvtoDataFrame('test.csv')
df2=df.readcvs()
print(df2)
I have a class which I want to use to extract data from a text file (already parsed) and I want do so using dynamically created class methods, because otherwise there would be a lot of repetitive code. Each created class method shall be asociated with a specific line of the text file, e.g. '.get_name()' --> read a part of 0th line of text file.
My idea was to use a dictionary for the 'to-be-created' method names and corresponding line.
import sys
import inspect
test_file = [['Name=Jon Hancock'],
['Date=16.08.2020'],
['Author=Donald Duck']]
# intented method names
fn_names = {'get_name': 0, 'get_date': 1, 'get_author': 2}
class Filer():
def __init__(self, file):
self.file = file
def __get_line(cls):
name = sys._getframe().f_code.co_name
line = fn_names[name] # <-- causes error because __get_line is not in fn_names
print(sys._getframe().f_code.co_name) # <-- '__get_line'
print(inspect.currentframe().f_code.co_name) # <-- '__get_line'
return print(cls.file[line][0].split('=')[1])
for key, val in fn_names.items():
setattr(Filer, key, __get_line)
f = Filer(test_file)
f.get_author()
f.get_date()
When I try to access the method name to link the method to the designated line in the text file, I do get an error because the method name is always '__get_line' instead of e.g. 'get_author' (what I had hoped for).
Another way how I thought to solve this was to make '__get_line' accepting an additional argument (line) and set it by passing the val during 'the setattr()' as shown below:
def __get_line(cls, line):
return print(cls.file[line][0].split('=')[1])
and
for key, val in fn_names.items():
setattr(Filer, key, __get_line(val))
however, then Python complains that 1 argument (line) is missing.
Any ideas how to solve that?
I would propose a much simpler solution, based on some assumptions. Your file appears to consist of key-value pairs. You are choosing to map the line number to a function that processes the right hand side of the line past the = symbol. Python does not conventionally use getters. Attributes are much nicer and easier to use. You can have getter-like functionality by using property objects, but you really don't need that here.
class Filer():
def __init__(self, file):
self.file = file
for line in file:
name, value = line[0].split('=', 1)
setattr(self, name.lower(), value)
That's all you need. Now you can use the result:
>>> f = Filer(test_file)
>>> f.author
'Donald Duck'
If you want to have callable methods exactly like the one you propose for each attribute, I would one-up your proposal and not even have a method to begin with. You can actually generate the methods on the fly in __getattr__:
class Filer():
def __init__(self, file):
self.file = file
def __getattr__(self, name):
if name in fn_names:
index = fn_names[name]
def func(self):
print(self.file[index][0].split('=', 1)[1])
func.__name__ = func.__qualname__ = name
return func.__get__(self, type(self))
return super().__getattr__(name)
Calling __get__ is an extra step that makes the function behave as if it were a method of the class all along. It binds the function object to the instance, even through the function is not part of the class.
For example:
>>> f = Filer(test_file)
>>> f.get_author
<bound method get_author of <__main__.Filer object at 0x0000023E7A247748>>
>>> f.get_author()
'Donald Duck'
Consider closing over your keys and values -- note that you can see the below code running at https://ideone.com/qmoZCJ:
import sys
import inspect
test_file = [['Name=Jon Hancock'],
['Date=16.08.2020'],
['Author=Donald Duck']]
# intented method names
fn_names = {'get_name': 0, 'get_date': 1, 'get_author': 2}
class Filer():
def __init__(self, file):
self.file = file
def getter(key, val):
def _get_line(self):
return self.file[val][0].split('=')[1]
return _get_line
for key, val in fn_names.items():
setattr(Filer, key, getter(key, val))
f = Filer(test_file)
print("Author: ", f.get_author())
print("Date: ", f.get_date())
I have the following issue, I am trying to define a new class, and I have just created new methods an attributes, but when I try to return the values I have some issue like: "objects is not callable", "XXX is not an attribute of the class", etc. I imported all the libraries out of the class:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
(...)
Then just read the data:
charge = pd.read_csv('iris.csv',delimiter=';',decimal=",")
print(charge)
Then just decided to work with numeric variables as following:
data = charge.iloc[:, 0:4].values #
dataval= charge.iloc[:, 4].values
print(data)
print(dataval)
And everything looks great until this: when I defined my class
class mynew_ACP:
def __init__(self, data):
self.__data = data
#property
def data(self):
return self.__data
#datos.setter
def data(self, data):
self.__data = data
def trasformation(self, data):
col = StandardScaler().fit_transform(self.__data)
col2= pd.DataFrame(col)
return col2
def correlation_var(self, data):
corr = data.corr()
return corr
But when I tried to call the methods to see the values I do not have anything. I have. tried with this code:
acp = mynew_ACP(data)
acp.data()
acp.trasformation()
acp.correlation_var()
Got error as mentioned in the beggining. I am new using Python and I do not know where is/are my issues. Tried with parenthesis and brackets but did not work.
Any help?
I'm new to python.I'm getting "main instance has no call method" error in the below code.I'm trying to create product class objects in main class and call product class function using these objects. What is the correct way to do this to not get such error.
import sys
from sys import argv
class read():
def __init__(self):
return
def read_function(self):
self.file_one=open(argv[1],"r")
self.file_two=open(argv[2],"w")
return self.file_one,self.file_two
class product():
def calculate(self,calc_row):
self.calc_row=calc_row
if "India" in calc_row[3]:
print "In India"
self.tax_amt=int(calc_row[2])*5/100
self.final_amt=self.tax_amt+int(calc_row[2])
elif "US" in calc_row[3]:
print "In US"
self.tax_amt=int(calc_row[2])*10/100
self.final_amt=self.tax_amt+int(calc_row[2])
else:
print "In UK"
self.tax_amt=int(calc_row[2])*15/100
self.final_amt=self.tax_amt+int(calc_row[2])
return self.tax_amt,self.final_amt
def writerow(self,out_file,list,tax_am,final_am):
self.list=data
self.tax_am=tax_val
self.final_am=final_val
self.out_file=out_data
self.string=",".join(self.list)
self.string=self.string+","+str(self.tax_am)+","+str(self.final_am)+"\n"
print self.string
self.out_file.write(self.string)
class main():
def __init__(self):
return
def main_function(self):
read_obj=read()
self.in_data,self.out_data=read_obj.read_function()
self.prod_list = [product() for i in range(3)]
for self.index,self.line in enumerate(self.in_data):
if (self.index == 0):
self.header=self.line
self.header=self.header.replace("\n","")
self.header=self.header+",Sales_Tax,Final_Price \n"
self.out_data.write(self.header)
else:
self.line.replace("/n","")
self.data=self.line.split(",")
self.prod=self.prod_list[index-1]
self.tax_val,self.final_val=self.prod.calculate(self.data)
print "Tax %d Final %d"% (self.tax_val,self.final_val)
self.prod.writerow(self.out_data,self.data,self.tax_val,self.final_val)
product=main()
product.main_function()
write_obj=write()
print type(prod_list[0])
When you write
product = main()
you replace the class that is bound to product with an instance of main. Later, when you try to create an instance of product, you are actually attempting to call the instance of main as a function.
You need to use a different name, and the simplest way to do that is to follow the convention that user-defined class names start with uppercase letters, and all other names (excluding CONSTANTS) start with lowercase names.
import sys
from sys import argv
class Read():
...
class Product():
...
class Main():
...
# This is a bad name, by the way. If you have two classes named Product
# and Main, a variable named product seems far more likely to be an
# instance of Product, not Main.
product = Main()
product.main_function()
As they answered you on comments
class product():
conflicts with
product=main()
so product is not a class name anymore. Please make your classes' first letter uppercase or better take a look at PEP8
I have a some bunch of python files. I need to get all the classes from there and make a list.
its like I have to read with streamreader and then
Imports ActionBlock
I have to take the string ActionBlock and show it in a list. Listing and others hopefully I can do, but I am stuck in this point. Any suggestion please? Thank you.
You could use a regular expression to look for the parts you're interested in.
The following code
Dim path = "c:\path\to\your\file.py"
Dim content = File.ReadAllText(path)
Dim matchClass = "class (?<m>\w+)(:|\()+"
Dim matchImport = "(^|from \w+ )import ((?<m>\w+), )*(?<m>\w+)"
Dim result = Regex.Matches(content, String.Format("({0}|{1})", matchClass, matchImport), RegexOptions.Multiline) _
.Cast(Of Match) _
.SelectMany(Function(m) m.Groups("m").Captures.Cast(Of Capture).Select(Function(c) c.Value)) _
.ToList()
will, given a text file like
import os
import math
from time import clock
from random import randint
import DataArchiving
import TABasicFunctions
import HWDataConveterGate
import GeneralTestDataMapping
from something import FirstClass, SecondClass
def foo():
pass
def bar():
pass
class ClassOne(object):
class NestedClass:
pass
def thisisnotaclass(self):
v = [x.class for x in self]
v = [x.someimport for x in self]
class ClassTwo:
pass
class Class3:
pass
def main():
pass
if __name__ == '__main__':
main()
create a list that looks like: