845 questions
0
votes
3
answers
96
views
If I subclass int, how to make arithmetic methods return the derived type?
I want to construct objects which support arithmetic operations and have extra methods, e.g:
class Timestamp(int):
def as_seconds(self):
return self / 90000
The extra method works:
>&...
0
votes
1
answer
66
views
In subclassing an edit box using SetWindowLongPtrA() to pass a function address, I get an "incompatable type" error
I'm trying to subclass an edit box in a dialog in VS C++ 2022. I want to intercept any key presses in a particular edit box to do further processing.
Here's my code. The 4th line confuses me because I ...
1
vote
2
answers
118
views
How to prevent Javascript super constructor calling a method overridden by a derived class?
I'm new to JS and implementing a polymorphic class hierachy. It appears that within the super constructor (when called from a derived constructor), 'this' refers to the derived class, not the super ...
0
votes
1
answer
106
views
How can I subclass a TButton to owner-draw it?
I want to color a TButton control in C++Builder. I am trying to follow the information I found that suggests using SetWindowLong() to enable the BS_OWNERDRAW style for my TButton control, then catch ...
0
votes
0
answers
107
views
SetWindowSubclass on Windows 10 Notepad
I've been trying to solve this little problem the whole day, and I can't figure out what's wrong. I suppose this is a simple problem for some. So I'm trying to Subclass Notepad with a procedure that ...
1
vote
1
answer
73
views
subclass tuple in Python to simulate infinite repeating sequence?
I have a sequence of 16 elements (dealer and vulnerability of bridge boards, to be specific) that repeat endlessly in theory (in practice it almost never gets past 128, and rarely past 36).
That is, ...
0
votes
0
answers
64
views
What is the best way to access immutable part when subclassing immutable type?
Suppose that you want to create a new subclass for float, using the following code:
class MyFloat(float):
def __new__(cls,number,extra):
return super().__new__(cls,number)
def ...
1
vote
1
answer
209
views
Subclass of pathlib.Path doesn't support "/" operator
I'm attempting to create a subclass of pathlib.Path that will do some manipulation to the passed string path value before passing it along to the base class.
class MyPath(Path):
def __init__(self, ...
1
vote
1
answer
279
views
Tensorflow 2.17 - Saving custom model does not work for me
(tensorflow 2.17, Windows 10)
I can't save and restore a custom model using subclassing method.
Please find below the code to reproduce the problem :
import numpy as np
import tensorflow as tf
x = np....
1
vote
1
answer
116
views
How does JavaScript "decide" how to print a class name?
I'm trying to write an inheritence logic where I clone an input class and inherit from remaining parent classes. In order to do that, I need to create a new class, deep copying one of the classes ...
0
votes
0
answers
53
views
Is it possible to define a subclass in python that creates a new atomic attribute?
I'll call an "atomic" attribute of a python class to be one from which all other user defined attributes derive. For example, the attribute a in the class below is atomic to A because all ...
1
vote
0
answers
175
views
Adding a method to an existing enum in Python
I have an existing enumeration with a number of values defined in package b, and I want to add behavior in the current package a. I understand that you can't directly subclass an enum with existing ...
1
vote
0
answers
89
views
CMFCButton with transparent background
I have developed a class that subclasses from CMFCButton. I load three PNG images (with transparent zones) to the button foreground in the DrawButton function for three states:
Normal
Hovered
Pushed
...
1
vote
0
answers
39
views
Subclassing Pandas Series without losing original methods
I'm trying to implement my subclass of pd.Series, but original pd.Series methods don't work as expected and return Nan
class Subclass(pd.Series):
# see https://pandas.pydata.org/pandas-docs/stable/...
1
vote
2
answers
88
views
Is there a simple way to subclass python's set without redefining all operators?
Is there a way to subclass set, with the binary operator returning the subclassed type, without redefining them ?
example :
class A(set):
pass
a = A([1,2,3]) & A([1,2,4])
a.__class__ == A # ...
0
votes
0
answers
22
views
In Pyside2, when I subclass QSqlTableModel how do I write the data method without generating maximum recursion depth errors? [duplicate]
I have a working application in Pyside2 that displays a QSqlTableModel in a QSqlTableView.
Three of the fields display raw seconds, like "6282" meaning six thousand and some seconds into a ...
0
votes
0
answers
70
views
why the output of the tape.gradient is None? (Tensorflow)
EPOCHS = 10
LR = 0.001
loss_object = MeanSquaredError()
optimizer = Adam(learning_rate = LR)
load_metrics()
@tf.function
def trainer():
global train_ds, train_loss, model
global optimizer, ...
0
votes
1
answer
81
views
Subclassing dict to give it inital values from a JSON file doesn't work as expected
I come from a C/C++ background
I would like to subclass dict to make one that automatically opens a JSON file.
Here's the code and problem:
class DictFromJSON(dict):
def get_from_file(self, ...
1
vote
1
answer
168
views
How to automatically forward class instance methods to another object's methods?
Regarding the following example code, is there any type-safe way of automatically forwarding any of the prototypal method calls, each to its related method of another object?
class Foo {
greet() {
...
0
votes
0
answers
52
views
overwrite np.ndarray __getitem__
Target
I'm dealing with 2D time-series data, and never use negative indexing. So I want to subclass np.ndarray that negative and out-of-bound indexing in axis 0 will return a nan-augmented matrix with ...
3
votes
1
answer
66
views
Is an empty subclass of UIAlertController safe for use with `appearance(whenContainedInInstancesOf:)`
Somebody here on SO wanted to alter the behavior of UIAlertAction buttons in a specific UIAlertController, but not others. (They wanted multi-line button labels for one alert but normal behavior for ...
0
votes
3
answers
872
views
How to dynamically create a subclass from a given class and enhance/augment the subclass constructor's prototype?
I have an unusual situation where I need to dynamically generate a class prototype then have a reflection tool (which can't be changed) walk the prototype and find all the methods. If I could hard ...
1
vote
1
answer
190
views
TS reuse this.constructor in parent method
I have a base Message class and an subclass SpecializedMessaged for extra features
class Message {
constructor(
readonly content: string
) { }
edit(replacement: string) {
...
1
vote
1
answer
146
views
How does ndarray.__new__ know from where it is being called?
In the numpy documentation of subclassing ndarray here. It is said that
ndarray.__new__, passes __array_finalize__ the new object, of our own
class (self) as well as the object from which the view ...
0
votes
0
answers
30
views
Considerations when replacing a Mixin with abstract Model subclass?
I have multiple Models that all need some shared functionality.
My existing code uses a Mixin class:
class MyMixing:
some_class_variable = None
@classmethod
def get_headers(cls):
...
1
vote
1
answer
122
views
Unexpected type warning in `__new__` method for `int` subclass
The following code:
class Foo(int):
def __new__(cls, x, *args, **kwargs):
x = x if isinstance(x, int) else 42
return super(Foo, cls).__new__(cls, x, *args, **kwargs)
...
1
vote
1
answer
149
views
Why is class and subclass reduction a particular consequence of the Prototype design pattern?
I read the Design Patterns book (written by the Gang of Four) and I'm now recapping on the Prototype Design pattern. In the consequence section, of the Prototype design pattern, (explained on page 119 ...
1
vote
1
answer
64
views
How can I find out if a user is trying to maximize a window before it happens with subclassing?
I'm trying to catch a message in a subclassed form and make a new event from it so I can check things before it happens and then cancel the message if needed.
I want to know if the user is trying to ...
1
vote
1
answer
866
views
Subclassing dict and implementing __getitem__ for nested class (python)
I am currently trying to implement a subclass (called 'Pointer_dict') for the python dictionary class dict. The purpose of this class is to save memory when creating copies of dictionaries and ...
1
vote
2
answers
520
views
Is there a way to extend two classes with the same method that references super?
I'm creating a subclass of the NodeJS http.Agent to get rid of the queuing behavior when it has reached the socket limit. I've overridden addRequest to track the number of concurrent requests per ...
0
votes
2
answers
254
views
Subclass a Python class with predefined parameters in one liner
Given a simple class:
class MyClassA():
def __init__(self, param_a, param_b):
self.param_a = param_a
self.param_b = param_b
def my_method(self, param_c):
...
1
vote
2
answers
455
views
PyCharm incorrectly assumes object is instance of BaseClass after calling issubclass()
I am running this test with Python 3.10.9 and PyCharm 2022.2.1 (Community Edition). This is an issue with PyCharm, not Python itself.
In my example code, I use a generator method that takes in a class ...
0
votes
1
answer
355
views
subclassing int in a Cython extension type using __new__
I want to cythonize code that uses a subclass of "int", which behaves actually like a set (similar to C++ bitset).
The pure python object is instantiated with __new__:
class BitSet(int):
...
0
votes
1
answer
158
views
Inheriting from type and typing.Mapping: "TypeError: descriptor '__subclasses__' of 'type' object needs an argument"
I am trying to define a class that is supposed to simultaneously do two things:
serve as the metaclass for a dataclass
act like a mapping
i.e., it will need to be derived from both type and typing....
1
vote
1
answer
469
views
Problems using Keras Model Subclassing, input shape=<unknown>
Currently I am learning subclassing with Keras. Thus far I have built my models using the functional API. For the paper I try to recreate at the moment subclassing would be really helpful though.
My ...
1
vote
1
answer
269
views
Declare symbols local to functions in SymPy
I have a custom Sympy cSymbol class for the purpose of adding properties to declared symbols. This is done as follows:
class cSymbol(sy.Symbol):
def __init__(self,name,x,**assumptions):
...
1
vote
3
answers
572
views
How do I force a PyTorch tensor to always satisfy some (possibly arbitrary) property?
I would like to subclass torch.Tensor to make tensors that will always satisfy some user-defined property. For example, I might want my subclassed tensor to represent a categorical probability ...
0
votes
0
answers
20
views
Automatic attribute copying from member class to parent class at class definition using ABC's __init_subclass__ in Python
I have this code:
from abc import ABC
class ConfigProto(ABC):
def __init__(self, config_dict):
self._config_dict = config_dict
def parse(self, cfg_store: dict) -> None:
# ...
1
vote
1
answer
194
views
Typescript Overriding Type of String Literals
I currently have the following setup:
enum EnumA {
A,
AYE
}
enum EnumB {
B,
BEE
}
type A = keyof typeof EnumA
type B = keyof typeof EnumB
type AB = A | B
interface IBase {
foo:...
0
votes
1
answer
25
views
I have a base class and an internal subclass with an external subclass in another adjacent file, only the internal subclass shows in __subclasses()
My base class and internal subclass in c2base.py
class C2Methods(object):
_instruction = {}
_request = {}
_paramter = {}
_data = {}
_responsedata = {}
def init(self, instruction, ...
0
votes
1
answer
38
views
The all method not see the instance field values for subclassing keras.Model [closed]
For subclassing to create a Tensorflow model with the following code:
class MyClass(keras.Model):
def __int__(
self,
input_shape: tuple,
classes_count: int = 10,
...
1
vote
1
answer
1k
views
How to hook WndProc in WINUI
Over the years, I've hooked the WndProc in everything from VB3 to C# in WinForms with no issue, but WINUI-3 and C# is giving me problems.
My DLL Imports are:
/// <summary>
/// ...
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://...
2
votes
1
answer
160
views
Performance penalty when overriding Numpy's __array_function__() method
I wrote an array-like class 'Vector' which behaves like an 'np.ndarray' but has a few extra attributes and methods to be used in a geometry engine (which are omitted here).
The MVP below overrides '__ ...
3
votes
0
answers
59
views
Raise an Event within an Excel-Addin when a Userform is loaded by the Excel Application or other Addin
I need to detect from within an excel-addin when a userform is loaded into memory without using the Initialize- or Activate-event of the loaded userform.
I'm currently trying to extend an Excel app by ...
2
votes
1
answer
232
views
PyQgis: item is not the expected type on a QgsMapCanvas
I am currently working on a PyQgis based standalone application and I need to add various QgsRubberBand to my Canvas.
I made a subclass of it : LineAnnotation.
The problem is that when I use the ...
4
votes
0
answers
156
views
Why is WM_TOUCH not received when I do something lengthy in the touch down event?
I am subclassing a window, and I process the WM_TOUCH messages.
When I receive a WM_TOUCH message, I call
Dim RetVal&
RetVal = GetTouchInputInfo(hTouchInput, TouchPoints, tiTouchInput(1&), ...
0
votes
2
answers
85
views
How to invoke a public method depending on a certain instance property?
I'm learning Typescript and I'm trying to run method in a class.
I have a Class Person, and two classes which extends the Person Class: Man and Woman.
I also have an array of persons, and I need ...
0
votes
1
answer
676
views
Swift - Subclassing URLSessionDataTask - Which super.init(DataTaskFakeWrapper: URLSessionDataTask ?????????) Apply?
I'm trying to subclass a URLSessionDataTask as shown in this post Initializer does not override a designated initializer while subclassing NSURLSession Swift Except that the sub class init imposes a ...
3
votes
1
answer
2k
views
Subclassing URLSession - 'init()' was deprecated in iOS 13.0
I would like to create a subclass of URLSession, but I get a warning:
'init()' was deprecated in iOS 13.0: Please use +[NSURLSession sessionWithConfiguration:] or other class methods to create ...