Which superclass class is super().__init__(**kwargs) calling?
In the following code I instantiate RightPyramid as:
p = RightPyramid(base=2, slant_height=7)
p.area()
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
super().__init__(**kwargs)
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
class Square(Rectangle):
def __init__(self, length, **kwargs):
super().__init__(length=length, width=length, **kwargs)
class Triangle:
def __init__(self, base, height):
self.base = base
self.height = height
super().__init__()
def tri_area(self):
return 0.5 * self.base * self.height
class RightPyramid(Square, Triangle):
def __init__(self, base, slant_height, **kwargs):
self.base = base
self.slant_height = slant_height
kwargs["height"] = slant_height
kwargs["length"] = base
super().__init__(base=base, **kwargs)
def area(self):
base_area = super().area()
perimeter = super().perimeter()
return 0.5 * perimeter * self.slant_height + base_area
def area_2(self):
base_area = super().area()
triangle_area = super().tri_area()
return triangle_area * 4 + base_area
The RightPyramid _mro_ results in:
(__main__.RightPyramid,
__main__.Square,
__main__.Rectangle,
__main__.Triangle,
object)
My question is:
What is super()._init_(**kwargs) in Rectangle class calling? I think it calls the init from Triangle class, but Rectangle does not inherit from Triangle class; on the other hand it precedes Triangle in MRO
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Infinite loop in a C++ constructor
I've got this class in c++ and I'm having trouble with the second constructor: for some unknown reason, the IDE is acusing an infinite loop. I don't have any idea what is causing it, since I've written similar loops countless times. The code in question is this:
class ArithmeticProgression : protected Progression{ //Constructors explicit ArithmeticProgression(double reason) : Progression(){ this->reason = reason; } ArithmeticProgression(double reason, int maxIndex) : Progression(){ this->reason = reason; for(int i = 0; i < maxIndex; i++){ } } //Destructor ~ArithmeticProgression(){ delete this; } protected: double reason; };
-
What is "does not name a type" error and how it can be resolved
#include <bits/stdc++.h> using namespace std; class Item{ unordered_map<string,int> mp; mp["Pizza"]=50; mp["Burger"]=100; mp["Coke"]=50; mp["Brownies"]=60; public: int getPrice(string s) { return mp[s]; } }; class Day{ std::unordered_map<string,int> hr; hr["Peak hour"]=30; hr["Night Charges"]=20; hr["Special days"]=50; hr["Normal"]=20; public: int getHrPrice(string s) { return hr[s]; } }; int main() { double totalBill=0; Item i; Day d; totalBill+=i.getPrice("Burger"); totalBill+=i.getPrice("Coke"); totalBill+=totalBill*5/100; totalBill+=d.getHrPrice("Special"); totalBill+=d.getHrPrice("Night"); cout<<totalBill<<endl; return 0; }
I'm getting this error :
error: ‘mp’ does not name a type
error: ‘hr’ does not name a type
I'm new to OOPS. Thanks in Advance...
-
Opengl GLFW3, Cant update vertices of two object at the same time
So i am trying to make a game where I want to update my player and enemy. enemy and player are squares. I have a square class with VAO, VBO, EBO and vertices where I load my square.
void Square::loadSquare() { unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // bind vertex array object glBindVertexArray(VAO); // bind vertex buffer object glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW); // bind element buffer objects // EBO is stored in the VAO glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // registered VBO as the vertex attributes glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // unbind the VAO glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); }
and draw method:
void Square::drawSquare() { // Bind the VAO so OpenGL knows to use it glBindVertexArray(VAO); // Draw the triangle using the GL_TRIANGLES primitive glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); }
Player and Enemy classes are inherited from square class and they have their own update method where I call in my Carte classes update methode.
void Carte::update(){ drawMap(); enemy.update(GrapMap,0); player.update(GrapMap); }
In draw map I simply draw my enemy and player.
void Carte::drawMap(){ enemy.drawSquare(); player.drawSquare(); for(auto & wall : walls){ wall.drawSquare(); } }
Walls are squares too but in my case I draw therm where I want and I don't have a problem with them. at the end of every update of enemy and player after chancing vertices of them I call
glBindBuffer(GL_ARRAY_BUFFER, VAO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW);
When it was only player that I was updating it was working flawlessly. But with enemy I cant see the player but I can see that its vertices are changing accordingly to the key input of the user. When I comment out player and try to update enemy only enemy is not updating but again I can see its vertices changing as it should.
Before creating my Carte object at the main I did this:
// Vertex Shader source code const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; //Fragment Shader source code const char* fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(0.8f, 0.3f, 0.02f, 1.0f);\n" "}\n\0"; int main() { // Initialize GLFW glfwInit(); // Tell GLFW what version of OpenGL we are using // In this case we are using OpenGL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Tell GLFW we are using the CORE profile // So that means we only have the modern functions glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create a GLFWwindow object of 800 by 800 pixels, naming it "window" GLFWwindow* window = glfwCreateWindow(1000, 1000, "Window", NULL, NULL); // Error check if the window fails to create if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } // Introduce the window into the current context glfwMakeContextCurrent(window); //Load GLAD so it configures OpenGL gladLoadGL(); // Specify the viewport of OpenGL in the Window // In this case the viewport goes from x = 0, y = 0, to x = 800, y = 800 //glViewport(0, 0, 1400, 1400); // Create Vertex Shader Object and get its reference GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); // Attach Vertex Shader source to the Vertex Shader Object glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); // Compile the Vertex Shader into machine code glCompileShader(vertexShader); // Create Fragment Shader Object and get its reference GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); // Attach Fragment Shader source to the Fragment Shader Object glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); // Compile the Vertex Shader into machine code glCompileShader(fragmentShader); // Create Shader Program Object and get its reference GLuint shaderProgram = glCreateProgram(); // Attach the Vertex and Fragment Shaders to the Shader Program glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); // Wrap-up/Link all the shaders together into the Shader Program glLinkProgram(shaderProgram); // Delete the now useless Vertex and Fragment Shader objects glDeleteShader(vertexShader); glDeleteShader(fragmentShader);
In my while loop I am doing this:
// Specify the color of the background glClearColor(0.07f, 0.13f, 0.17f, 1.0f); // Clean the back buffer and assign the new color to it glClear(GL_COLOR_BUFFER_BIT); // Tell OpenGL which Shader Program we want to use glUseProgram(shaderProgram); int keyW = glfwGetKey(window, GLFW_KEY_W); int keyA = glfwGetKey(window, GLFW_KEY_A); int keyS = glfwGetKey(window, GLFW_KEY_S); int keyD = glfwGetKey(window, GLFW_KEY_D); carte.update(); if(keyW) deneme.setPlayerDirection(Directions::UP); else if(keyA) deneme.setPlayerDirection(Directions::LEFT); else if(keyS) deneme.setPlayerDirection(Directions::DOWN); else if(keyD) deneme.setPlayerDirection(Directions::RIGHT); // Swap the back buffer with the front buffer glfwSwapBuffers(window); // Take care of all GLFW events glfwPollEvents();
I don't understand why I can't update my two objects at the same time. Why I cant draw squares as the vertices changes when there is more then one objects vertices are changing.
edit to show how I change my vertices in Player:
if(getDirection() == Directions::UP){ trans = glm::translate(trans, glm::vec3(0.0f, 0.0002f, 0.0f)); setCenter(center.first,center.second + 0.0002f); } else if (getDirection() == Directions::LEFT){ trans = glm::translate(trans, glm::vec3(-0.0002f, 0.0f, 0.0f)); setCenter(center.first-0.0002f,center.second); } else if (getDirection() == Directions::DOWN){ trans = glm::translate(trans, glm::vec3(0.0f, -0.0002f, 0.0f)); setCenter(center.first,center.second-0.0002f); } else if (getDirection() == Directions::RIGHT){ trans = glm::translate(trans, glm::vec3(0.0002f, 0.0f, 0.0f)); setCenter(center.first+0.0002f,center.second); } else if (getDirection() == Directions::STOP) trans = glm::translate(trans, glm::vec3(0.0f, 0.0f, 0.0f)); for(int i=0; i < 4; i ++){ glm::vec4 tmp = trans * glm::vec4(getVertices()[i],1); setVertices(i, tmp.x, tmp.y, tmp.z); } glBindBuffer(GL_ARRAY_BUFFER, VAO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW);
-
"Crossing the hierarchy" -- why not?
We have a multiple inheritance hierarchy:
// A B // \ / // C //
Both
A
andB
are abstract classes. C is actually a templated class, so downcasting is near impossible if you have aB
and you want to access a member of it as anA
.All
A
's andB
's must beC
's, since that is the only concrete class in the hierarchy. Therefore, allA
's must beB
's, and vice versa.I'm trying to debug something quickly where I have a
B
that I need to accessA::name
of. I can't downcast toC
because I don't know the templated type of it. So I'm writing code like below and surprisingly it doesn't work; and I'm wondering what gives.struct A { virtual void go() = 0; std::string name; }; struct B { virtual void go() = 0; }; struct C : A, B { void go() override { } }; int main() { C c; c.name = "Pointer wonders"; puts(c.name.c_str()); // Fine. B* b = (B*)&c; //puts(b->name.c_str()); // X no from compiler. A* a1 = (A*)&c; puts(a1->name.c_str()); // As expected this is absolutely fine // "Cross" the hierarchy, because the B really must be a __C__, because of the purely virtual functions. // neither A nor B can be instantiated, so every instance of A or B must really be a C. A* a2 = (A*)b; puts(a2->name.c_str()); // Why not?? // If you downcast first, it works C* c2 = (C*)b; A* a3 = (A*)c2; puts(a3->name.c_str()); // fine }
-
How to call the method of a parent class in python?(Snowflake methods)
I have a file
SF.py
.class SnowflakeDatabase(Database): def __init__(self): self.ctx = None # ctx will be initialize by start_connection() self.db = None # db will be initialize by start_connection() def start_connection(self): sf_host = #initialize all those values sf_username = #same as above sf_password = #same as above sf_warehouse =#same as above sf_database = #same as above self.ctx = snowflake.connector.connect( user=sf_username, password=sf_password, account=sf_host, insecure_mode=True ) self.db = self.ctx.cursor() def run_query(self, query: str): self.db.execute(query)
In another file,
example.py
,from SF import SnowflakeDatabase db = SnowflakeDatabase(v, log) db.start_connection() query = ''' Select * from any_table ''' db.run_query(query) #This runs self.db.execute(query)
Now, I want to execute the inbuilt method 'fetchall' directly from
example.py
. II cannot include a function like the following in the base class in
SF.PY
.def fetch_query(self, query: str): self.db.fetchall(query)
and run like
run_query
.I have to execute the method in the direct way or some other way. No changes can be made in the base class.
-
In a Python multiple inheritance situation, why do the root classes need to call super().__init__()?
Why is the presence of
super().__init__()
in the base classes necessary for thesuper().__init__()
in the child class to run through both inheritance branches?The code below illustrates what happens with and without
super().__init__()
in the base classes:import sys #-------------------------------- class one(): def __init__(self): super().__init__() print("one") class two(): def __init__(self): super().__init__() print("two") class three(one,two): def __init__(self): super().__init__() print("three") #-------------------------------- class uno(): def __init__(self): print("uno") class dos(): def __init__(self): print("dos") class tres(uno,dos): def __init__(self): super().__init__() print("tres") print("python version") print(sys.version) print("---------------") a = three() print("---------------") b = tres()
Output:
python version 3.8.12 (default, Aug 30 2021, 16:42:10) [GCC 10.3.0] --------------- two one three --------------- uno tres
-
why we use super() in java subclass constructor to call superclass constructer?
I didn't use super() in my subclass constructer(Dog) to call the superclass constructor(Animal) but why did the compiler show the output as "Animal constructor". I just want to know why run Animal constructer without using super() keyword
class Animal{ Animal(){ System.out.println("Animal constructor"); } } class Dog extends Animal{ Dog(){ System.out.println("dog constructor"); } } public class Main{ public static void main(String[] args) { Dog d = new Dog(); } }
-
Typescript Super is undefined when running unit tests with jest
I use super.catch inside catch from derived class. And code works fine when I do manual testing. But when I run jest unit tests it says that super is undefined. Does anyone know why? And how it can be fixed?
Code example:
export class CustomExceptionsFilter extends BaseExceptionFilter { catch(exception: Error | HttpException, host: ArgumentsHost) { logger.error(exception); super.catch(exception, host); } }
Unit test example:
beforeEach(async () => { filterInstance = new CustomExceptionsFilter(); host = mockArgumentsHost; }); it('Test', async () => { const baseClassSpy = jest.spyOn(CustomExceptionsFilter.prototype, 'catch'); const httpException = new HttpException('Test exception', 404); filterInstance.catch(httpException, host); expect(baseClassSpy).toHaveBeenCalled(); });
Error I get:
TypeError: Cannot read properties of undefined (reading 'reply') 35 | 36 | logger.error(exception); > 37 | super.catch(exception, host); | ^ 38 | } 39 | }
-
Multilevel and Multiple inheritance using super() in Python returns odd result
if I type this this code,
class A: pass class B(A): def show_letter(self): print("This is B") class C(B): def show_letter(self): super().show_letter() print("This is C") class E(B): def show_letter(self): super().show_letter() print("This is E") class D(C, E): division = "North" def show_letter(self): super().show_letter() print("This is D") div1 = D() div1.show_letter()
it returns:
This is B This is E This is C This is D
Why is there "E" printed ? If I delete super() in C class, "E" is not printed. Thank you.