105 questions
0
votes
1
answer
44
views
Python( Gotcha?) - Element gets appended to multiple list items, in a list of list [duplicate]
I've recently hit a gotcha in Python. I've added a minimal example. Can somebody tell me what is happening?
a = [list()] * 3
print(a)
#[[], [], []]
a[0].append(1)
print(a)
#Out - [[1], [1], [1]]
#...
-1
votes
1
answer
75
views
How to extract each value seperately from the object 'best_params_' returned by gridsearch method by sklearn?
I am using gridsearch in sklearn using the following code
How should I extract each numeric value i.e. 44.984326689694534 or 0.2811768697974237 from the object grid.best_params_?
param_grid= {'gamma': ...
0
votes
0
answers
86
views
How to call Inner Class?
Is there any difference between call Person.Name() and self.Name() despite Person.Name() being more readable?
class Person:
class Name:
def __init__(self, first_name, last_name):
...
0
votes
0
answers
130
views
Handling of long living python objects in docker container, remote controll of objects
I am developing a design which works on top of a docker network topology. It emulates netwrok elements talking to each other using udp packets.
On host the big controller script is executed. It brings ...
0
votes
3
answers
1k
views
How do I create two objects in Python with different identities but the same value? [duplicate]
I can't seem to be able to create two strings that have the same value but different identities.
I'm using PyCharm 2023.1 and I'm very new to Python, I've just learned about the difference between == ...
0
votes
1
answer
66
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
128
views
Django: How to create "Published" and "Last edited" fields?
I'm writing a blog for my portfolio and I wanna compare (in the Django template) the date I published an article with the date I edited it in order to display the "Edit date" only if it was ...
0
votes
1
answer
49
views
Dynamically set Node, Python3 - BinaryTree module
I was experimenting with graphs in python and i felt into a problem.
Here is the code :
class IspNetwork :
def __init__(self) -> None:
self.root : Node = Node("isp")
def ...
0
votes
0
answers
24
views
Including another object inside an object and calling a specific value
I'm trying to make a simple 5v5 sport management, but I'm not sure how can I link players to teams, in order to make the overall rating of the team be the sum of the players rating / amount of players....
0
votes
2
answers
213
views
What is the value of <object name>.<method name> in Python?
Consider the following code.
class Foo:
def bar(self, x):
pass
foo1 = Foo()
foo2 = Foo()
foobar1 = foo1.bar
foobar2 = foo2.bar #What are foobar1 and foobar2?
print(foobar1 ...
3
votes
2
answers
2k
views
type(x) is list vs type(x) == list
In Python, suppose one wants to test whether the variable x is a reference to a list object. Is there a difference between if type(x) is list: and if type(x) == list:? This is how I understand it. (...
0
votes
1
answer
109
views
i have an error python OOP. Python magic method __div__() [duplicate]
I have "TypeError: unsupported operand type(s) for /: " for this code
class add_object:
def __init__(self, num) -> None:
self.x = num
def __div__(self, other):
...
0
votes
1
answer
238
views
in Python/iPython, is there any way to access or call an object or variable properties from solely its name within a list?
I have a Jupyter Notebook. I know it's not optimal for large works but for many circumstances, is the tool I have to use.
After some computations, I end up with several pandas DataFrame in memory that ...
0
votes
0
answers
77
views
Accessing other classes attributes in Python
I want to design specific class hierarchy consisting of three classes: Certificate, Organization, User. Both Certificate and Organization seem to me to be kinda "equal" (they are each others ...
1
vote
4
answers
1k
views
how to create a python object where every attribute is None
I'm not sure if this can be done, but I would like an object where you can query any attribute, and it just returns None, instead of an error.
eg.
>>> print(MyObject.whatever)
None
>>&...
0
votes
1
answer
419
views
How to move ContextFilter class for logging to separate module?
I have ContextFilter Class in my python script which I am using to have a counter variable in log formatter. It works as expected and prints value of incremented variable in log.
But when I try to ...
1
vote
2
answers
3k
views
Is there a way to disable some function in python class so that it cannot be used except using it in inside its class? [duplicate]
for example i have myClassFile.py file with code as follow:
class myClass:
def first(self):
return 'tea'
def second(self):
print(f'drink {self.first()}')
then i have run.py ...
1
vote
2
answers
606
views
Pythonic way to get either one of two attributes from a Python object
I want to get either one of two attributes from a Python object. If neither of those attributes is present, I want to get a default value.
For instance, I want to get either the number of apples or of ...
0
votes
0
answers
41
views
Cython cannot convert to Python object [duplicate]
cdef class Y:
cdef double* _ptr
def __cinit__(self, double* ptr):
self._ptr = ptr
cdef class X:
cdef double* _ptr
def __cinit__(self):
# some magic with _ptr
...
0
votes
0
answers
94
views
Storing tkinter objects in MySQL
Let me give you some context first.
I am making a project using tkinter, python and MySQL. In my project, every time the user clicks on create button in the tkinter window(which i will be calling root ...
6
votes
3
answers
3k
views
Python multiprocessing making same object instance for every process
I have written a simple example to illustrate what exactly I'm banging my head onto. Probably there is some very simple explanaition that I just miss.
import time
import multiprocessing as mp
import ...
0
votes
0
answers
127
views
This a working code from a course I have enrolled, Can you help me understand the part where I have added a comment against the line in script?
def get_event_date(event):
return event.date
def current_users(events):
events.sort(key=get_event_date)
machines = {}
for event in events:
if event.machine not in machines:
machines[...
1
vote
0
answers
433
views
Assigning starting player and switching between them
I am trying to assign a starting player as the "first" CurrentPlayer, and then assign player 2 as CurrentPlayer once player 1 has finished the turn. Somehow, I cant get it to work at all.
...
0
votes
1
answer
381
views
How to assign image components in pyvips?
I am using the pyvips library which has a special object for images, these objects have the 3 bands corresponding to HSV (or other) colour space components. The problem is that, after filtering one of ...
1
vote
1
answer
53
views
How to find out what `*` operator do on two objects from some library (cirq)?
I just started using python cirq library and I came across the following line of code in the tutorial:
XX_obs = cirq.X(q0) * cirq.X(q1)
I just want to find in the code what this * operator do on this ...
0
votes
3
answers
885
views
How to make a Python class properties accesible by index?
I have a Django model like this:
class Competitor(models.Model):
"""
Competitor model object
"""
name = models.CharField(max_length=20)
easy = ArrayField(models....
0
votes
1
answer
228
views
How to find the minimum from a list of objects?
I want to write a method to find the minimum scored person and print his other details.
If I write a method to find minimum I can't print his other details.
In question, it is told that to write "...
1
vote
2
answers
432
views
How is this Python design pattern called?
In the ffmpeg-python docs, they used following design pattern for their examples:
(
ffmpeg
.input('dummy.mp4')
.filter('fps', fps=25, round='up')
.output('dummy2.mp4')
.run()
)
...
1
vote
1
answer
375
views
DJANGO python error return qs._result_cache[0]
Im new using Django, Im coding for an ecommerce and everything is working as expected but an error raised even when the code is working!
Sorry for spanglish:
id = request.POST.get('id')
tamano = ...
3
votes
1
answer
269
views
Loading same-named classes with importlib based on directory name: What are the consequences?
Of course "no consequences except the obvious" is a valid answer to my question about the consequences.
I help maintain a code base, with some proposed code structured roughly like this:
# ...
1
vote
0
answers
21
views
Override a sloted attribute with a class variable in python [duplicate]
The code below:
class A(object):
__slots__ = 'a'
def __init__(self, a):
self.a = a
print (A(4).a) # 4
class B(A):
a = 4
__slots__ = 'b'
B(4)
blows with:
Traceback (most ...
0
votes
1
answer
44
views
Why does the it not update the circle should move one to the right?
import random, pygame
#window setup aswell as global variable
pygame.init()
screen_size = 400
global window
window = pygame.display.set_mode((screen_size,screen_size))
pygame.display.set_caption("...
0
votes
1
answer
728
views
Using Python multiprocessing to run object computations
I need to do run some computations to update object attributes. I want to use parallel computing since I need to update multiple objects' attributes, that is, I have multiple objects and I need to do ...
4
votes
2
answers
1k
views
Is "everything" in Python (3) an instance of some class?
I am new to Python but have already read a number of times the principle that everything in Python is an object.
Does that mean that everything is an instance of some class?
As an example, suppose we ...
0
votes
1
answer
17
views
Having trouble updating database with Django
Hey guys my code is a bit jumbled but maybe you can help me sort out why it's not doing what I want it to do.
There's something wrong with my logic since I have tried the update statements on their ...
0
votes
0
answers
69
views
Pandas object with timestamps to string
I have a pandas dataframe with a column iso in datetime64[ns] format. My goal is to first convert this column to the ISO 8601 format, and then to a plain string.
dtrain.shape
(10886, 12)
dtrain....
0
votes
0
answers
75
views
Python defined 'types' - intermediate dev pet peeve
TLDR: This is a specific question about best approach to coding a common need in Python, of creating non-flat 'types' - one that IMHO (as 3 year intermediate level python dev) is probably the greatest ...
0
votes
5
answers
4k
views
How to assign Python Dict Keys to corresponding Python Object Attributes
Suppose I have a python class like:
class User:
name = None
id = None
dob = None
def __init__(self, id):
self.id = id
Now I am doing something like this:
userObj = User(...
0
votes
1
answer
30
views
Two different object instance printing same result of first instance
I have the following code:
from iqoptionapi.stable_api import IQ_Option
def fun(mail, password):
acc = IQ_Option(mail, password)
acc.connect()
return acc.get_balance()
acc.api.close()
...
0
votes
1
answer
222
views
Pyspark use customized function to store each row into a self defined object, for example a node object
Is there a way to utilize the map function to store each row of the pyspark dataframe into a self-defined python class object?
pyspark dataframe
For example, in the picture above I have a spark ...
0
votes
2
answers
406
views
Create a bunch of objects from files in a directory
I have made a class that I'm using to manipulate and work with my data.
class DataSet():
def __init__(self, path, label_names, ohe_names, random_state=420):
self.df = pd.read_csv(path)
...
-3
votes
1
answer
180
views
python functions with no return from the functions [duplicate]
What is the type of the object that Python functions use, when a function does not return a "useful" object?
For example:
from time import sleep
sleep(2)
1
vote
1
answer
75
views
I want to call parent class method which is overridden in child class through child class object in Python
class abc():
def xyz(self):
print("Class abc")
class foo(abc):
def xyz(self):
print("class foo")
x = foo()
I want to call xyz() of the parent class, ...
0
votes
1
answer
93
views
Copying a class instance to another with python
I have a function which returns an object of class Person, defined as:
class Person:
def __init__(self):
self.id=None
self.age=0
self.name=None
def setValues(self,id,...
1
vote
4
answers
987
views
Is there a way to override the print method in Python 3.x?
Pretty simple question - I have searched but not found an answer to this question.
It might be a bit silly to do this but I was curious if it is possible to hook into the print(*arg, **kwarg) ...
0
votes
1
answer
307
views
How to ignore duplicate object values from display
I have a test class with 3 attributes, a,b,and c.
3 instances of the class has been created with values set for the attributes appropriately,
Its given that 'a' attribute is always unique and when two ...
0
votes
1
answer
37
views
How can I call an attribute of an object using something the user has entered?
'''
class python_object:
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
#object_dict is made by importing JSON ...
0
votes
0
answers
92
views
Print Python class objects with attributes in another python file using user input
Main Python code Class:
main.py
class Dog():
name = ""
location = ""
barks = False
NotNaughty = False
def __init__(self, name, **kwargs):
self.name = name
class Cat():
...
0
votes
1
answer
279
views
Immutable objects with same value and type not referencing same object
I have been reading the Python Data Model. The following text is taken from here:
Types affect almost all aspects of object behavior. Even the
importance of object identity is affected in some ...
-1
votes
1
answer
294
views
How to dump user defined python objects to json file? By Objects I mean actual objects and not their attributes
So I have two user defined python classes shown below
class cell(object):
def __init__(self,id,x_cor,y_cor,width = cell_size,height = cell_size ,color = lightblue ):
self.id = id
self.x_cor = ...