Questions tagged [python-class]
For questions that relate to the use of classes as a language feature in Python.
python-class
505
questions
0
votes
2
answers
49
views
Python decorators with class methods
I want a decorator that I can use as both @decorator and decorator() with class methods, like this :
def decorator_with_args(name):
print(f'Hello {name} !')
def decorator(func):
def ...
0
votes
0
answers
32
views
Having a problem with calling the class twice
import tkinter as tk
import math,time,random
from PIL import ImageTk, Image,ImageEnhance
start_time = time.time()
window = tk.Tk()
window.geometry("300x300")
canvas = tk.Canvas(window, ...
1
vote
3
answers
65
views
How to display an image with classes in tkinter?
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
window.geometry("300x300")
canvas = tk.Canvas(window, width=300, height=300,bg="red")
canvas.pack()
class ...
0
votes
0
answers
98
views
OpenAI API upgrade from 0.28 to 1.x
I am trying to upgrade the OpenAI 0.28 version to 1.2.2. For doing that I defined the client and replaced the openai chatcompletion with client.
Below is the constant file which will be used in the ...
0
votes
1
answer
33
views
How can I substitute an imported python class in a .py file without modifying the file itself?
What I'd like to achieve is:
b.py(might be in a third party package I cannot modify):
from xxx import A
class B:
def __init__():
self.a = A()
The file I actually execute:
execute.py
...
0
votes
3
answers
44
views
For class created from Python turtle module, instead of return functions at each method, how can data created from a method be used in different one?
For a class (snake class) created from the turtle module in Python:
Problem 1.
when the move() method is called, the snake segments are moving backwards instead of forward . The problem seems to be ...
-1
votes
1
answer
83
views
How to add class variable values to a list, python 3x?
I'm trying to add class variable values to a list inside a function, but I'm not seeing any errors or the expected output? The comboxbox doesn't display when I uncomment the list code.
Outside of the ...
0
votes
0
answers
34
views
Unable to properly initialize a tkinter scrollbar inside a UI
I'm not an expert python programmer. After some time and effort I've built a tkinter UI that properly works. Recently, I've found myself needing to add a scrollbar inside the frame, since I need to ...
0
votes
3
answers
46
views
How to run multiple instances of an object with two threads inside each object?
I'm trying to wrap two threaded functions inside an object and run a couple of instances of the object. So far I could only run the objects if I pull the threading outside the class.
import threading
...
0
votes
2
answers
244
views
List all properties defined on a Pydantic BaseModel
Is there an elegant way to list all properties defined on a Pydantic BaseModel?
It's possible to extract the list of fields via BaseModel.model_fields and the list of computed fields via BaseModel....
1
vote
2
answers
66
views
On demand Python imports
I have the following situation: A module that contains a class Foo with some additional convenience functions for assembling Foo objects. A Foo object contains methods for interacting with data in an ...
0
votes
1
answer
110
views
Programatically create multiple instances of CustomTkinter Combobox Python
New to python and trying to create an app with customtkinter. The app lets users pick values from different drop-downs and generates codes based on the chosen value.
Updated per comment from Mike-SMT:
...
4
votes
3
answers
202
views
How to correctly define a classmethod that accesses a value of a mangled child attribute?
In Python, how do I correctly define a classmethod of a parent class that references an attribute of a child class?
from enum import Enum
class LabelledEnum(Enum):
@classmethod
def ...
2
votes
1
answer
35
views
Python convert class instance variable to nested structure
Defining a class of instance variable from commonly used fields in API response by looping through each JSON record
self.id=response['identifier'] -->output: 1234
self.name=response['...
0
votes
0
answers
102
views
ValueError: Attempt to convert a value (class) with an unsupported type (class) to a Tensor
these codes were running flawlessly on tensorflow==2.15, for the purpose of GPU acceleration, I switched to tensorflow-gpu == 2.10.1 with keras 2.10, respectively. and this ValueError raised up on my ...
1
vote
1
answer
100
views
ROS (Robot Operating System) simple publisher and subscriber using class in python
I am trying to run a simple code in ROS to create a subscriber and a publisher using classes in python. I am new to using classes in python and I am not sure what I am doing wrong here.
Below is the ...
0
votes
0
answers
39
views
Updating class attributes in python
I have two classes Player and LineUp, one is used within the other (shown below). I am trying to update my LineUp class after I have already instantiated it.
class Player:
def __init__(self, ...
0
votes
2
answers
47
views
How can I retain a reference to the parent object when creating an instance of a nested class through the outer object in Python?
Is it possible to retain a reference to the parent object when creating an instance of a nested class through the outer object, without explicitly passing the parent object as an argument?
class ...
0
votes
1
answer
44
views
How is class Franchise, linked with Class Menu? in Below Python Code?
What informs the code that The relationship between the Franchise and Menu classes is that The Franchise class has an attribute menus that stores instances of the Menu class, when clearly Menu and ...
0
votes
1
answer
62
views
Quit Tkinter application by calling class method
I am trying to build a splash screen that I will be able to call from an external application using Tkinter. I'd like to define my GUI in a class, like this:
class Splash:
def __init__(self):
...
0
votes
1
answer
413
views
Error while using a custom class in Python: 'AttributeError: 'module' object has no attribute 'MyClass
I'm facing an issue while working with a custom class in Python. I have a module named 'my_module' with a class called 'MyClass'. However, when I try to instantiate the class in another script or ...
-2
votes
1
answer
429
views
Python Selenium AttributeError: object has no attribute
The problem is although i can see the method I'm calling, the error says I don't have a method the way I call. Here is the error:
Traceback (most recent call last):
File "C:\Users\htuna\...
0
votes
0
answers
25
views
In python class, how to pass returned value of a method of a class as input to another method of the same class
I am using boto3 library to establish connection to an s3 compatible storage. I had created a class with constructor that take cluster details, access key & IDs as inputs, having these initiated. ...
0
votes
1
answer
82
views
How to delete an instance of a class using a function?
I am looking for a way to create a method within a class that will delete that particular instance.
I know one way to do is by using del keyword but I want to make it user interaction based so that ...
0
votes
1
answer
64
views
Understanding this class intialization in python
I have this piece of code, part of a Spikingjelly neural network training functionality, which gets some errors on this line after running. I'm not quite experienced in Python, and I don't understand ...
-2
votes
2
answers
103
views
Why are these 2 python class instance could equal to each other?
from dataclasses import dataclass
@dataclass
class ThreeDPoint:
x: int | float
y = 0.0
z: int | float = 0.0
point_1 = ThreeDPoint(1.0,2)
point_3 = ThreeDPoint(1,2)
print(point_1 == ...
0
votes
1
answer
58
views
A script changes the source code of class. Why can the effect not be observed in the same console or test, where the script was run?
I have written a script, that automatically adds a property to a class.
It works, but currently I can not test it.
The code is shown below, but can also be seen on GitHub.
See the class Cat,
the ...
0
votes
0
answers
28
views
how I can describe that my function return (or need) a object with same type that the class I'm building? [duplicate]
I'm newbie with typing on Python, and I'm have an unexpected problem. This is a random example, but describe the problem it self
With this code:
class Location:
def __init__(self, name: str) -> ...
0
votes
0
answers
23
views
Capture exception for all class methods with class decorator don't work for init method
I want to capture all the methods of Myclass(and give them a new exception type)
I created a class decorator to implement this but the exception handling doesn't cover the __init__
How can I fix this? ...
0
votes
1
answer
116
views
Automatically calling class function after init
I want to automate a class method which would be called right after __init__ has completed.
e.g,
class A:
def __init__(self):
initialization statement
def post_init(self):
#...
0
votes
1
answer
400
views
Decorate all functions of a Python class while being able to access the class attributes within the decorator
I've got a class and would like to apply a decorator to all functions within that class without having to add a function decorator to every single function.
I know that there are solutions like the ...
-1
votes
2
answers
80
views
Struggling with class methods, cls, and self when using functions cross classes in python while updating a dictionary
I am trying to build a small UI for updating some settings and then displaying some intake data on a raspberrypi. Python version is 3.9.2. The most logical way to save the settings I thought would be ...
0
votes
2
answers
42
views
Turtle doing nothing in embedded Tkinter window
I am trying to make a program in which you can draw different shapes. I already managed to embed the turtlescreen into my already existing Tkinter one (root) and got a Tkinter Menu, in which I can run ...
0
votes
0
answers
13
views
How to print a list from a Class. List for the jetta attributes [duplicate]
Unable to print 'jetta' list that is within this class. I don't know how to print it.
Class Car
name = jetta
Should I enter return somewhere?
class Car:
model = []
model2 = []
...
1
vote
1
answer
68
views
Python overload __setitem__ does not replace self out of the class range
I am trying to create a kind of dataframe subclass with inheritance of polars.DataFrame. I would like to modify the __setitem__ method to make following statement possible:
df['test_column'] = 'test'
...
0
votes
1
answer
102
views
DataFlow Code returning empty output for DoFn class
I am trying to run the below code using dataflow, where I have 2-3 functions defined inside a class, out of which 2 functions are working but the send_email() is working nor throwing any errors.
...
0
votes
3
answers
106
views
What is the logic of changing class variables?
The following code was supposed to clarify how Python class variables behave,but somehow it opens more questions than it solves.
The class Bodyguard has the variable protect, which is a list that by ...
-1
votes
1
answer
65
views
I developed a class for generating images, but I have a type problem (name 'train_step' is not defined) that I can't
Here's the complete class code with an example of its implementation.
import tensorflow as tf
import numpy as np
import time
from tensorflow.keras.applications.inception_v3 import InceptionV3
from ...
0
votes
0
answers
74
views
Tkinter result page with possible cyclic dependency
I'm having trouble creating a results page for a tkinter GUI that I've made. The problem is that the page2 file has to import the page3 file in order to go to page3 when clicked with a button. In the ...
1
vote
1
answer
468
views
Method for correct/pythonic way to use @cached_property to set a permanent attribute on a Python class
I am trying to set a permanent attribute on a class to be used by other methods throughout the life of the instance of the class
class Test:
@cached_property
def datafile_num_rows(self) -> ...
0
votes
0
answers
30
views
return json in python class
I have this class and function in python to monitor file creation and i want to retrieve the result as json:
import win32api
from watchdog.observers import Observer
from watchdog.events import ...
0
votes
1
answer
48
views
Merge private attributes in Python
I know that private attributes are loosely defined in Python, but I'm trying to figure out what would be the most lean way of implementing a method to merge together private attributes.
Class Event:
...
1
vote
2
answers
141
views
Python - pass arguments when adding a button to plot's toolbar (matplotlib)
I am trying to add a button to toolbar. The button is a custom class that inherits ToolToggleBase. In my custom SelectButton class, I want to pass few arguments, but I getting an error:
import numpy ...
1
vote
1
answer
576
views
Pandas "DataFrame"s as class properties. How should I initialize them in class constructor __init__()?
I have a class which will manage multiple pandas Data Frames. The Data frames are class properties. I have initiated every Data Frame in the class constructor and assigned an empty Data Frame to them (...
0
votes
0
answers
32
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
45
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
27
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
532
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
118
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 ...