510 questions
0
votes
0
answers
33
views
How to fix Python problem with embedded class definitions
Working on LeetCode #1032, I'm having a problem that appears related to having embedded classes. Here is the code:
from collections import deque
class StreamChecker:
def __init__(self, words):
...
0
votes
0
answers
46
views
Sleep Function Inside FOR Does Not Perform One-by-One Counting [duplicate]
I'm practicing creating classes and functions in Python. In a certain simple countdown exercise, I had to use the sleep() function inside a FOR loop to display the numbers one by one. The issue is ...
0
votes
1
answer
64
views
Attribute error when trying to going back and forth between functions in Python
I'm getting the error "AttributeError: 'NoneType' object has no attribute 'name'" for the code below:
class Student:
def __init__(self, name, house):
if not name:
...
0
votes
1
answer
47
views
Python: conserving list structure when working with Composition-Composite classes
How to conserve list structure when working with Composition in Python?
For instance,
class Population:
'''Defines a population of Colonies'''
def __init__(self, Nc, ...):
self....
0
votes
1
answer
710
views
Get init arguments of child class from parent class
getInitInpArgs on ann gets the input arguments in init of ann to a dictionary. Now I want to define a function like getInitInpArgs on ann (parent class) and not on the child classes, which makes a ...
1
vote
1
answer
260
views
The class name with or without quotes in a Django model field to have foreign key relationship
I can set Category with or without quotes to ForeignKey() as shown below:
class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model): # Here
category ...
0
votes
1
answer
525
views
How can I use cogs (discord.py)
I'm quite new to Python, but I understand how cogs work.
But what do I have to write in the main-File (to load all the cogs in a subfolder of my main.py) and what do I have to write in the cog?
And ...
0
votes
1
answer
236
views
Asynchronous Response from python class function
I was able to successfully use an Mailgun example to send an e-mail, but when converting to a class, the e-mails are not being sent. I am assuming that it has to do with the Asynchronous Response but ...
0
votes
1
answer
100
views
How to resolve ModuleNotFoundError when importing a local Python file?
I am studying python. I'm trying to do a simple exercise from the course I'm studying. I tried to separate the classes into different files to make it easier to keep track of the inheritance and to be ...
0
votes
1
answer
57
views
Can you force derived class from a bass class to define specific member variables in python?
If I have a class say:
class BaseClassOnly():
def __init__(self):
self._foo = None
def do_stuff(self):
print("doing stuff with foo" + self._foo)
I want to force all ...
1
vote
0
answers
47
views
Overriding a method definition with a method from another class?
class test:
def func(self):
print(5)
class test1:
def testing(self, t):
t.func = self.another_func
def another_func(self):
print(6)
t = test()
t1 = test1()
t1.testing(t)
# now t....
0
votes
1
answer
44
views
Incremental ID in class returns incorrect ID when multiple instances of the class are used in a pipeline
Trying to add an ID attribute to a class that increments for each instance. Each instance is then passed into a pipeline, which is producing some unexpected results.
A reproducible example looks like ...
0
votes
0
answers
5k
views
How can I create one-to-many relationships in SQLAlchemy Flask?
How do I create a one-to-many relationship in a Flask SQLAlchemy database?
My db class:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, ...
0
votes
1
answer
91
views
How to access Object values in Python
For this function:
def kmeans(examples, k, verbose = False):
#Get k randomly chosen initial centroids, create cluster for each
initialCentroids = random.sample(examples, k)
clusters = []
...
0
votes
1
answer
83
views
Function "doesn't recognise" a python class method
I have written a class that creates a board for a Klotski game and I want to use breadth-first search to solve the given problem. Here is a bit of my code:
EDIT and DISCLAIMER: I added all the ...
0
votes
1
answer
184
views
How can I access the class attribute name via the class itself to improve readability and type hinting in Python?
Suppose you have the following classes:
class MyClass:
attribute1: str
attribute2: int
class MySecondClass:
another_attribute1: str
another_attribute2: int
I want to access the string ...
0
votes
1
answer
87
views
How to inherit one class implement by C
I want to add method for one class implemented by C
from lru import LRU
class A(LRU):
def foo(self):
print("a")
lru is a lib from https://github.com/amitdev/lru-dict
error:“...
1
vote
0
answers
61
views
Accessing object attributes and methods from other modules
I have a GUI application I've been developing as an exercise in Python. The application is structured as a package. I initially create an instance of the application, which creates an instance of a ...
0
votes
2
answers
162
views
Custom method decorator aware of a class [duplicate]
I had an idea for a simple decorator that would probably not be very useful (feel free to comments on that, but it's not my main focus here). Regardless of that, I think it'd show how to achieve ...
-4
votes
1
answer
107
views
How to call a method of a class in python? [closed]
With below code I am trying to find the oldest of the 3 cats. When I try to call the method 'cat_age' of class 'Cat' in the print statement it gives the below error:
NameError: name 'cat_age' is not ...
2
votes
2
answers
1k
views
Python "on_destroy" class method
I am wondering if there is a way to call a method before the object is finally "destroyed" - like some sort of event.
I am using a class and a static method. Since it is not an instantiated ...
0
votes
2
answers
670
views
Mapping class methods of python class
I created a message class, which stores an arbitrary message like so:
class MessageBase:
"""Wrapper class for messages from different resources"""
def ...
1
vote
2
answers
226
views
How to generate methods to set and get properties at class instantiation with Python?
I have a class containing tensors that have an unpredictable list of properties.
I would like it to generate a list of properties with getters and setter based on a list given at instantiation.
Do hou ...
0
votes
1
answer
48
views
scope strangeness in python class attributes
Came across what seems to be a weird case of 'spooky action at a distance' using python class attributes.
If I define X as:
class X():
a = list()
b = int
def __init__(self, value):
...
1
vote
1
answer
74
views
is "correct" or pythonic, this way of make getters or is better to use @property? [duplicate]
I have a class where the attribute is a numpy array, and a lot of getters, for several slices of that array.
The question is about what is a more pythonic way of doing this
def get_right_knee(self) -&...
0
votes
0
answers
1k
views
Terminate tkinter process when "X" button is clicked (python)
I am coding a small GUI project in python. While the process is running, if the user clicks the "X" button then I keep getting alerts like "app not responding" in python. After I ...
-2
votes
1
answer
96
views
I cannot define a function inside my class
I am trying to define a function inside of my class but still on line 31 'command=clear' does not see my function i created below. Please help, thank you!!
import tkinter as tk
from tkinter import *
...
1
vote
1
answer
183
views
How to access attributes of a Python class as one would access fields of a Matlab structure in an iterative context
In Matlab, let's consider a structure "structure" and a list of fields "list_of_fields".
structure = struct;
list_of_fields = ["a","b","d"]; % Some ...
0
votes
3
answers
54
views
copy.deepcopy(): Class with dictionary copied improperly
Good evening!
I faced a problem with copy.deepcopy(). I wanted to copy a class which had dict self variable and got this result:
>>> import copy
>>> class A:
... a = {'a': 1}
... ...
0
votes
2
answers
92
views
Python: how to find out what parameters are needed for class of heavy inheritance?
A simplified code looks like this:
class Base:
def __init__(self, *, a, b, c, d, **kwargs):
...
class Level1_1(Base):
def __init__(self, *, e, **kwargs):
super().__init__(a=e**...
1
vote
2
answers
127
views
Making interdependent and auto-updating attributes in a Python class
I'm trying to make a class with 2 or more mutually dependent attributes (e.g. a and a-plus-1). The idea is to be able to initialize an object with one and only one of these 2 attributes and the other ...
0
votes
0
answers
48
views
Pass a variable from class in another class in python
How can I pass a variable from class in another class in python?
I'm a beginner, I just started learning python and tkinter.
Example:
File main.py:
if __name__ == "__main__":
root = Tk()
...
1
vote
3
answers
93
views
Generating a random number (more than once) and using it inside two class functions
I am building a GUI with tkinter where two buttons modify two text fields. One button chooses a random key from the example_dict and displays it in text1 , and the other reveals the corresponding ...
1
vote
0
answers
84
views
How can i use multithreading in discord.py?
I've recently tried doing some image generating with craiyon's API, and send the image through discord.py,
But i realized that it takes a long time and it would stop the entire bot from working all ...
0
votes
2
answers
51
views
[Beginner Python]Issues trying to access a function within a class
I am trying to run a simple budget program and I am a complete beginner with classes in python. I am trying to run everything within the class so I can call back to specific functions. The problem is ...
0
votes
0
answers
178
views
Defining multiple versions a class method in python
I need to have a python class to execute different actions depending on a certain parameter passed by the user upon creating an instance of the class.
To avoid using if blocks, I defined different ...
1
vote
1
answer
461
views
How to clone a python class object? (not the instance but the class itself)
Imagine you have the following code:
class A:
pass
NewA = ... # copy A
NewA.__init__ = decorator(A.__init__) # but don't change A's init function, just NewA's
I am looking for a way to change ...
0
votes
1
answer
53
views
How to transfer an immutable part of a function to other projects
In the print_foo function, there is a part of the code that changes from project to project.
And there is a part of the code which is always the same. It is responsible for working with the Counter ...
1
vote
1
answer
81
views
Python decorate `class.method` that modify on `class.self`
How to access self of the decorated method?
Based on this answer, the self refer to the decorator:
class Decorator:
def __init__(self, func):
self.func = func
def __call__(self, *args,...
0
votes
0
answers
32
views
Is it ok to reference self.var in a parent class with the expectation it will be implemented in the child class? [duplicate]
I have some classes that look like this.
class Parent:
def f(self, x):
# Is this bad practice?
return x * self.number
class Child(Parent):
def __init__(self, number):
...
2
votes
3
answers
691
views
Can you modify an object's field every time another field is modified?
I have a dataclass that looks like this
from dataclasses import dataclass, field
@dataclass
class Data:
name: str | None = None
file_friendly_name: str | None = field(default=None, init=False)...
0
votes
0
answers
37
views
I am tryin to write Keith Galli's connect 4 code into different classes( each in a different .py file) and have difficulty passing to classes
I am trying to devide Keith Galli's Connect 4 with minmax algorithm into classes, so far I came up with 5 classes. Game-view, Main, Board, Minmax and Pieces. I know the best way to go about this was ...
0
votes
1
answer
712
views
AttributeError at type object 'Services' has no attribute 'app'
I newly started to develop Django. I want to connect my python algorithm and Django web ui so I tried to connect both of them in views.py but I encountered a problem.
It says AttributeError at type ...
0
votes
1
answer
209
views
Python3 Class Error: TypeError Employees() takes no arguments
I was unable to find an answer for this use case as it seems my syntax is correct. I think MAYBE my code isn't pulling the import correctly if my understanding (I'm still learning python basics) is ...
1
vote
1
answer
316
views
Dynamically creating serializable classes in Python
I am trying to update a class that is supposed to be used as a custom type for the multiprocessing.manager and imitate a basic dictionary. All works well on Linux, but things fail on Windows and I ...
0
votes
1
answer
44
views
Attibutes are 'disappearing' from CBV. Django
I am trying to build CBV with class View parent. This view takes slug of object and find that object between two django models. The functions from services.py was doing a lot of DB queries, so, I ...
1
vote
1
answer
131
views
Selenium opens chrome and shows error TypeError: 'str' object is not callable using Python Classe
Im making an auth bot, but I faced with a problem! When Im trying to start my selenium bot, it opens few tabs in Chrome and do nothing. It also print that
"str" object is not callable
Can ...
0
votes
1
answer
48
views
Python Mutli-Language XMLs as string resources
I want to implement language XML into my project and change all hard-code strings into language.xml references based on the way Android uses string resources. (I have not found anything that does this)...
0
votes
0
answers
21
views
Method inside a class printed without prompt [duplicate]
So I am following a tutorial and have the following code:
import random
class Coin:
def __init__(self, rare = False, clean = True, heads = True, **kwargs):
for key, value in kwargs.items(...
1
vote
0
answers
296
views
Subclass EarlyStopper in scikit-optimize
I can't figure out how to subclass EarlyStopper to use it as callback in scikit-optimize (gp_minimize). Based on the documentation. How should I think when subclassinging?
Documentation: https://...