I built a small demo script, which I want to import into another python script. The code is as follows:
class count:
def __init__(self):
def students(self,males,females):
return males + females
def teachers(self,bsc,nce):
return bsc - nce
def cleaners(self,older,younger):
return older + younger
class salary(count):
def __init__(self):
count.__init__(self)
def teachers_salary(self,teachers,amount):
return teachers * amount
def cleaner_salary(self,cleaners,amount):
return cleaners * amount
def gardeners_salary(self,gardeners,amount):
return gardeners * amount
I saved this script as count.py and I now want to import it into another script, so that I can use its modules. But when I use from count import salary and then run the code salary.teachers(bsc=10,nce=15), I get the error message below:
TypeError Traceback (most recent call last)
<ipython-input-62-b9aec73e51ba> in <module>
----> 1 print(salary.teachers(bsc=10,nce=15))
TypeError: teachers() missing 1 required positional argument: 'self'
Please, can someone advise me on what I am not doing right? Thanks as always.
Related
I´m trying to come up with a dynamic function calling system. I have a database with a bunch of differents levels:
Decision Evaluator > Function (response curve) parameters > Inputs.
Choosing a Decision Evaluator may call 10 different functions but only 5 inputs, treated differently through the parameters. So it would be way easier to have a dynamic system rather than create all the sub-calls for each main level.
In the test below, I can dynamically call a lower-level function from an upper level ('test'). When I try to pass arguments, I get the error 'str' object is not callable. Here's the trace:
C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\worksheet\_reader.py:312: UserWarning: Data Validation extension is not supported and will be removed
warn(msg)
Traceback (most recent call last):
File "C:\Users\*\considerations.py", line 28, in <module>
ich.dynamic_call(abcd_3(show_test))
TypeError: 'str' object is not callable
init ICH...
oouh weee look at me
Process finished with exit code 1
considerations.py:
from input_clearing_house import InputClearingHouse
import pandas as pd
inputs = pd.read_excel(r'AXIS_DB.xlsx', sheet_name='Inputs')
considerations = pd.read_excel(r'AXIS_DB.xlsx', sheet_name='Considerations')
decision_score_evaluator = pd.read_excel(r'AXIS_DB.xlsx', sheet_name='DecisionScoreEvaluator')
decision_maker = pd.read_excel(r'AXIS_DB.xlsx', sheet_name='DecisionMaker')
considerations = pd.merge(considerations, inputs, on='input_name')
# print(considerations)
ich = InputClearingHouse()
abcd_2 = 'test'
abcd_3 = 'multi21'
show_test = 'dynamite'
ich.dynamic_call(abcd_2)
ich.dynamic_call(abcd_3(show_test))
input_clearing_house.py:
import math
class InputClearingHouse:
def __init__(self):
print('init ICH...')
def dynamic_call(self, name, *args, **kwargs):
call_fct = f'{name}'
if hasattr(self, call_fct) and callable(func := getattr(self, call_fct)):
func(*args, **kwargs)
def test(self):
print("oouh weee look at me")
def multi21(self, *args):
for arg in args:
print(arg)
def distance_to_target(self, source: tuple, target: tuple) -> float:
return math.sqrt((source[0] - target[0]) ** 2 + (source[1] - target[1]) ** 2)
def my_endurance(self, current: int, maximum: int) -> float:
return current / maximum
abcd_3(show_test) is trying to use abcd_3 as a function, but it's a string that names a function.
ich.dynamic_call() expects the name and arguments of the function to call to be separate arguments, so you should use
ich.dynamic_call(abcd_3, show_test)
Your dynamic_call() method already copes with variable numbers of arguments.
I think you just meant to add arguments:
ich.dynamic_call(abcd_3, show_test)
i'm trying to solve the adventofcode riddles, but this year i decided to take the chance to learn a new programming language: Python.
Since i already have some knowledge about other OOP languages like Java and C++, i immediately created an "interface" system for the Solutions objects.
My project setup at the moment is like:
Project Setup
Now what i want is to dynamically output solutions through the main class, that basically has to call all .solve() method of each dayX.py class that is in the /solutions/ directory.
I think i'm next to do it but i get an error:
Traceback (most recent call last):
File "C:\Users\siste\j-workspace\adventofcode2020\main.py", line 16, in <module>
print(solution.solve())
TypeError: solve() missing 1 required positional argument: 'self'
Here are my files:
main.py
import os
def days():
classes = []
path = "C:\\path"
for file in os.listdir(path):
if(file.startswith("day")) :
classes.append(str(file.replace(".py", "")))
return classes
if __name__ == '__main__':
for day in days() :
solution = getattr(__import__(str("solutions." + day)), day.replace("d", "D"))
print(solution.solve())
solution.py
path = "C:\\path\\inputs\\day{}.txt"
class Solution:
def __init__(self, dayNumber):
self.dayNumber = dayNumber
self.inputPath = path.format(self.dayNumber)
def part1(self):
pass
def part2(self):
pass
def solve(self):
return ("Day {} Solutions: \n\tPart1: {}\n\tPart2: {}"
.format(self.dayNumber, self.part1(), self.part2()))
day1.py
import fileinput
from solutions.solution import Solution
class Day1(Solution):
def __init__(self):
super().__init__(1)
def part1(self):
return "sol"
def part2(self):
return "sol2"
When you're using the getattr on the imported module, you're getting the class definition. Methods are only callable on class instances, otherwise they throw the error you're seeing:
class A:
def a(self):
pass
A.a() // Will throw "TypeError: a() missing 1 required positional argument: 'self'"
A().a() // OK
Changing the __main__ part this way should solve the issue:
if __name__ == '__main__':
for day in days() :
day_class = getattr(__import__(str("solutions." + day)), day.replace("d", "D"))
day_instance = day_class()
print(day_instance.solve())
I am trying to improve my understanding of OOP in Python 2.7 (uses in my University courses). My goal is to print the outcome by using a child class. However, I keep getting the below error and do not know how to fix it and why it pops up.
Can anybody tell me how to fix this code and what I am doing wrong?
Error:
Traceback (most recent call last):
File "*******"", line 36, in <module>
print_grades = CreateReport(ReadFile)
TypeError: __init__() takes exactly 1 argument (2 given)
Code:
# Constants
input_file = 'grades1.in.txt'
class ReadFile():
def __init__(self):
self.text_file =''
def read_file(self, file):
self.text_file = open(file)
def data_to_list(self):
self.list_grades = []
for x in self.text_file:
output = x.strip("\n").split("\n")
temp_list = []
for y in output:
temp_list.append(y)
self.list_grades.append(temp_list)
return self.list_grades
class CreateReport(ReadFile):
def __init__(self):
# ReadFile.__init__(self)
pass
def print_list(self):
data = ReadFile.data_to_list()
print data
# start_program(input_file)
print_grades = CreateReport(ReadFile)
print_grades.print_list()
I am working with class object in order to improve my skills in programming.
I have three files *.py. Sorry for the basic example but help me to understand where my error is:
/my_work_directory
/core.py *# Contains the code to actually do calculations.*
/main.py *# Starts the application*
/Myclass.py *# Contains the code of class*
in Myclass.py
class Point(object):
__slots__= ("x","y","z","data","_intensity",\
"_return_number","_classification")
def __init__(self,x,y,z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
self.data = [self.x,self.y,self.z]
def point_below_threshold(self,threshold):
"""Check if the z value of a Point is below (True, False otherwise) a
low Threshold"""
return check_below_threshold(self.z,threshold)
in core.py
def check_below_threshold(value,threshold):
below = False
if value - threshold < 0:
below = not below
return below
def check_above_threshold(value,threshold):
above = False
if value - threshold > 0:
above = not above
return above
when I set main.py
import os
os.chdir("~~my_work_directory~~") # where `core.py` and `Myclass.py` are located
from core import *
from Myclass import *
mypoint = Point(1,2,3)
mypoint.point_below_threshold(5)
I get:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "Myclass.py", line 75, in point_below_threshold
return check_below_threshold(self.z,threshold)
NameError: global name 'check_below_threshold' is not defined
Functions in other modules are not automatically visible in your Myclass module. You need to explicitly import them:
from core import check_below_threshold
or import the core module and use that as a namespace:
import core
# ...
return core.check_below_threshold(self.z,threshold)
You have a missing import.
You have to import your functions where you use them.
That means, you have to import check_below_threshhold in the core.py too, because it gets used there.
What is the error below? Also, is there a better way to implement the following classes?
#!/usr/bin/python
class Datacenters:
def __init__(self,name,location,cpu,mem):
self.name=name
self.location=location
self.cpu=cpu
self.mem=mem
def getparam(self):
return self.name,self.location ,self.cpu,self.mem
def getname(self):
return self.name
class WS(Datacenters):
def __init__(self,name,location,cpu,mem,obj):
#datacentername = Datacenters.__init__(self) #To which data center it is associated
self.dcname =obj.name #To which data center it is associated
Datacenters.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
self.name,self.location ,self.cpu,self.mem = obj.getparam()
print self.dcname
#return self.name,self.location ,self.cpu,self.mem,obj.name
def getwsname(self):
return self.name
class Pcs(WS):
def __init__(self,name,location,cpu,mem,obj):
self.wsname = obj.getwsname() #To which WS it is associated
WS.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
print obj.getparam()
print self.wsname
a = Datacenters("dc1","Bl1",20,30)
print a.getparam()
b = WS("WS1","Bl1",21,31,a)
print b.getparam(a)
c = Pcs("PC1","Bl1",20,30,b)
#print c.getparam(b)
output:
Press ENTER or type command to continue
('dc1', 'Bl1', 20, 30)
dc1
None
Traceback (most recent call last):
File "class1.py", line 45, in <module>
c = Pcs("PC1","Bl1",20,30,b)
File "class1.py", line 34, in __init__
WS.__init__(obj,name,location,cpu,mem)
TypeError: __init__() takes exactly 6 arguments (5 given)
The error is that you pass in five arguments, but the __init__ needs six. Count them:
def __init__(self,name,location,cpu,mem,obj):
Six arguments. You call it like so:
WS.__init__(obj,name,location,cpu,mem)
Five arguments. The first one, self is missing. What you should ask yourself is why you don't have to pass in six arguments all the time.
And that is because self is passed in automatically when you call the method on an instance. However, in this case you don't call it on an instance, you call it directly on the class. There is of course no need to do so in this case, the correct syntax is:
WS(obj,name,location,cpu,mem)
As you indeed above note works further up.