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
3
votes
0 answers

Why am I getting an error for accessing an instance variable inside my class (python)

I am writing a class for a lazy square root, allowing me to use it in fractions for linear algebra without getting a messy float. I've run into two specific problems both related to pythons 'private' class attributes. The first is that I am getting…
3
votes
1 answer

How can I make __str__ or __repr__ return the current class's name?

I have this code: class Employee: def __init__(self, name, pay, gender): self.name = name self.pay = pay self.gender = gender def add_raise(self): self.pay = int(self.pay*1.10) def __str__(self): …
brightstar2100
  • 117
  • 1
  • 8
3
votes
1 answer

Why does this parent class setter call use type(self) rather than self?

Python @property inheritance the right way explains how to call the parent setter. class Number: def __init__(self): self._value = None @property def value(self): assert self._value is not None return…
mon
  • 18,789
  • 22
  • 112
  • 205
3
votes
1 answer

How to use self in an abstract class implementation in Python?

I'm working on a project using abstract classes in Python (specifically, the abc module). I have a few implementations of this abstract class, which have their own constructors and need to use self. This is what my code looks like, but…
jack.py
  • 362
  • 8
  • 23
3
votes
3 answers

Python (pandas): Using decorators using pandas API

I'm quite new to decorators and classes in general on Python, but have a question if there is a better way to decorate pandas objects. An an example, I have written the following to create two methods -- lisa and wil: import numpy as np import…
Mathew Carroll
  • 357
  • 3
  • 14
2
votes
2 answers

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 object, I cannot use del and modify __del__ on it. Is the…
Niv
  • 523
  • 1
  • 8
  • 19
2
votes
3 answers

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) def __post_init__(self): # If…
codeananda
  • 939
  • 1
  • 10
  • 16
2
votes
0 answers

Creating python classes

I have five python Classes in different files. All are in one folder. Folder -main.py -main_class.py -sub_of_first.py -sub_of_second.py -sub_of_third.py main.py start calls MainClass main.py def main(): model = MainClass(backbone, ) MainClass…
batuman
  • 7,066
  • 26
  • 107
  • 229
2
votes
1 answer

Why do instance variables and class variables return different output for this closure?

I have a closure that is supposed to save the return value of a computationally heavy function for reuse. However, when I run the exact same line of code (_ = cached_readonly_property(lambda: "b")), I get different return values based on whether the…
Jamie.Sgro
  • 821
  • 1
  • 5
  • 17
2
votes
1 answer

decorator that decorates @property and take arguments

My class (dataclass) has many properties that are calculations based on other properties or dataclass fields. I'm trying to create a decorator that takes a list of required fields or properties. That means they can't be None and can't return…
Milano
  • 18,048
  • 37
  • 153
  • 353
2
votes
2 answers

Problem with defining derived class in python

I am learning how to use classes in python to alter some Keras methods to create various forms of Generative Adversarial Networks, GANs. In this case, I am trying to implement the gradient penalty modification to the Wasserstein GAN architecture…
2
votes
0 answers

How to create a Python dataclass with a prop that depends on the output from a default_factory

I'm trying to use the dataclasses default_factory field to dynamically add a property (id) while also still being able to create a subsequent property (id_with_appended_str) whose default value depends on the former property (id) already being…
Jamie.Sgro
  • 821
  • 1
  • 5
  • 17
2
votes
1 answer

how to automatically create nested classes from arguments

I'd like to first provide a little bit of context. I have a dataframe that looks like: ID Q1 Q2 Q3 A Y N N A N N Y A N N N B Y Y N C N N Y C N N N D N N N D N N Y D N …
Schach21
  • 412
  • 4
  • 21
2
votes
0 answers

Python's free variables behaviour with inner classes

This is the challenge: x = 11 def foo1(): x = 2 class foo: print(x) foo1() # prints 2 x = 11 def foo2(): x = 2 class foo: print(x) x += 1 foo2() # prints 11 What is the explanation of this behaviour? Anyone?
mavaras
  • 53
  • 5
2
votes
2 answers

Reflected dunder method doesn't work for instances of the same type

Here is a small repro - class A and B are exactly the same, with the dunder method implemented for the reflected right shift operator. So, x >> y is expected to resolve to y.__rrshift__(x). class A: def __init__(self, x): self.x = x …
ananis
  • 43
  • 7
1
2
3
33 34