Questions tagged [python-class]

For questions that relate to the use of classes as a language feature in Python.

This tag is for questions that are about the use of classes in Python. Some aspect of the question should include a non-trivial inquiry related to the use of classes as a language feature. Do not use this tag just because the code happens to define or use a class.


From the official documentation on Python classes:

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

[...] Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation.

In C++ terminology, normally class members (including the data members) are public (except see below Private Variables), and all member functions are virtual. As in Modula-3, there are no shorthands for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call. As in Smalltalk, classes themselves are objects. This provides semantics for importing and renaming. Unlike C++ and Modula-3, built-in types can be used as base classes for extension by the user. Also, like in C++, most built-in operators with special syntax (arithmetic operators, subscripting etc.) can be redefined for class instances.

See also: Tag wiki for OOP

497 questions
2
votes
1 answer

Set class attribute by awaiting a coroutine in Python

I have a class that has an attribute that holds a Redis connection as seen below: import redis class RedisService: db = redis.Redis(host=RedisConfig.REDIS_HOST, port=RedisConfig.REDIS_PORT) @staticmethod def exists(key): return…
iedmrc
  • 742
  • 2
  • 8
  • 21
2
votes
1 answer

Python's asyncio.Event() across different classes

I'm writing a Python program to interact with a device based on a CAN Bus. I'm using the python-can module successfully for this purpose. I'm also using asyncio to react to asynchronous events. I have written a "CanBusManager" class that is used by…
2
votes
2 answers

Function Chaining in Python, ignore rest of chain if a segment returns False

The title pretty much explains the problem. I don't know if there's a practical solution to this or if I'm being too picky over the behavior of my code. This article was hinting in the right direction, but I never got any code to…
2
votes
1 answer

Implementing Typescript interfaces in Python

I'm looking for some advice on what's the best way of implementing a set of data value only 'interfaces' in Python that are equivalent to their typescript counterpart (we've got a project where we use both, and want to enforce a consistent interface…
Richard
  • 3,024
  • 2
  • 17
  • 40
2
votes
0 answers

Nested classes/functions that call one another and must inherit their parents' properties

I have a rather odd scenario, and I just can't wrap my head around the proper solution. I'm working on a project that has multiple functions to perform certain operations: These functions are interconnected and need to be able to call each other…
1
vote
1 answer

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' However, when I overload the __setitem__, it…
KYPcode
  • 13
  • 2
1
vote
2 answers

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 as np import matplotlib.pyplot as…
Alon123
  • 164
  • 3
  • 15
1
vote
1 answer

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 (Because Data Frames are not available at the…
Diaco
  • 38
  • 8
1
vote
1 answer

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 = models.ForeignKey("Category",…
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
1
vote
0 answers

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.func() uses test1's another_func and prints…
David
  • 619
  • 2
  • 8
  • 15
1
vote
0 answers

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 window, which contains layouts, which contain…
1
vote
2 answers

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 know how to do that ? Thanks class Items: …
Xiiryo
  • 3,021
  • 5
  • 31
  • 48
1
vote
1 answer

is "correct" or pythonic, this way of make getters or is better to use @property?

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) -> YoloV7PoseKeypoint: return…
Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84
1
vote
1 answer

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 specific fields of the structure and not all of them for field = list_of_field structure.(field)…
Valery
  • 25
  • 5
1
vote
2 answers

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 is updated simutaneously. Here is a minimal…
Xiasu Yang
  • 69
  • 5