How do you alias a python class to have another name without using inheritance?

If I have a python class, how can I alias that class-name into another class-name and retain all it's methods and class members and instance members? Is this possible without using inheritance?

e.g. I have a class like:

class MyReallyBigClassNameWhichIHateToType:
    def __init__(self):
         <blah>
    [...]

I'm creating an interactive console session where I don't want my users' fingers to fall off while instantiating the class in the interactive sessions, so I want to alias that really long class name to something tiny like 'C'. Is there an easy way to do this without inheritance?


Asked by: Lenny848 | Posted: 06-12-2021






Answer 1

C = MyReallyBigClassNameWhichIHateToType

Answered by: Ryan358 | Posted: 07-01-2022



Answer 2

Also, if you're importing the name from another module...

from modulename import ReallyLongNameWhichIHateToType as FriendlyName

Answered by: Lana837 | Posted: 07-01-2022



Answer 3

You can simply do:

ShortName = MyReallyBigClassNameWhichIHateToType

A class in Python is just an object like any other, and can have more than one name.

Answered by: Grace216 | Posted: 07-01-2022



Answer 4

Refactor the name, no reason it should have a name that long.

Otherwise whateverName = VeryLongClassName should do the trick.

Answered by: Stuart630 | Posted: 07-01-2022



Answer 5

Simple name assignment approach works but has one disadvantage that might be important in some cases: the alias name will be the same as the name of the "base" class because of the __name__ property.

class C(object):
    pass

D = C

print(C.__name__)  # 'C'
print(D.__name__)  # 'C' again

For example, if you create custom exception and then another one that assigning the first one you will get the name of this "parent" exception every time no matter which one of them you raise and this should probably confuse a user:

class CustomBaseException(Exception):

    def __init__(self, operation):
        super(CustomBaseException, self).__init__()
        self.operation = operation

    def __str__(self):
        return f"Invalid operation '{self.operation}'"


OperationException = CustomBaseException

raise OperationException('readd')

output:

Traceback (most recent call last):
  File "<input>", line 12, in <module>
CustomBaseException: Invalid operation 'readd'

So a solution would be to actually subclass the class:

class CustomBaseException(Exception):

    def __init__(self, operation):
        super(CustomBaseException, self).__init__()
        self.operation = operation

    def __str__(self):
        return f"Invalid operation '{self.operation}'"


class OperationException(CustomBaseException):
    pass


raise OperationException('delite')

output:

Traceback (most recent call last):
  File "<input>", line 14, in <module>
OperationException: Invalid operation 'delite'

Answered by: Ada235 | Posted: 07-01-2022



Similar questions

python - Single Table Inheritance in Django

Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good ...


Inheritance in Python

We just started learning about class inheritance and attribute lookup in python. I have a question about the following code: class a : n = 1 class b : n = 2 class c : n = 3 class d (a,b) : pass class e (d,c) : pass I know that e.n would equal 1 due to the nature of attribute lookup procedure (depth first search). However, how would I access, say, class c's n from class e? I've tried e.c.n,...


python - Tricky model inheritance - Django

I think this is a bit tricky, at least for me. :) So I have 4 models Person, Singer, Bassist and Ninja. Singer, Bassist and Ninja inherit from Person. The problem is that each Person can be any of its subclasses. e.g. A person can be a Singer and a Ninja. Another Person can be a Bassist and a Ninja. Another one can be...


python - inheritance from str or int

Why I have problem creating a class inheriting from str (or also from int) class C(str): def __init__(self, a, b): str.__init__(self,a) self.b = b C(&quot;a&quot;, &quot;B&quot;) TypeError: str() takes at most 1 argument (2 given) the same happens if I try to use int instead of str, but it works with custom classes. I need to use __new__ ...


python - Django model inheritance and type check

class Machine(models.Model): name= models.CharField( max_length=120) class Meta: abstract = True class Car(Machine): speed = models.IntegerField() class Computer(Machine) ram = models.IntegerField() My question is, how can I understand what type is the Machine model. For instamce I know the incoming query is a children of the Machine model but I also want to know it is a ...


python - user inheritance in django

I saw a couple of ways extending user information of users and decided to adopt the model inheritance method. for instance, I have : class Parent(User): contact_means = models.IntegerField() is_staff = False objects = userManager() Now it is done, I've downloaded django_registration to help me out with sending emails to new users. The thing is, instead of using registr...


python - Rails model inheritance

It will be simplest to explain with code example, in Python I can do so to achieve model inheritance: """Image model""" from sqlalchemy import Column, ForeignKey from sqlalchemy.types import Integer, String, Text from miasto_3d.model.meta import Base class Image(Base): __tablename__ = "image" image_id = Column(Integer, primary_key=True) path = Column(String(200)) def get_mime(self): ...


python - Django inheritance

Please have a look: class Categorie(models.Model): id = models.AutoField('id', primary_key=True) title = models.CharField('title', max_length=800) articles = models.ManyToManyField(Article) class Article(models.Model): id = models.AutoField('id', primary_key=True) title = models.CharField('title', max_length=800) slug = models.SlugField() indexPosition = models.IntegerField(...


python - Return from inheritance

How I update x.test to have values return from inheritance ? So I want x.test return ['test from B'', 'test from C'] class A() def __init__(self) self.test = [] return def coolThings(self): # do cool things here and print the new self.test print self.test class B(A) def __init__(self) A.__init__(self) return def doSom...


python - Django Model Inheritance and Admin System

I'm trying to build a system for managing the various types of content in a page. For example, a page may have text content, hyperlink content, video content, ect. In my modeling code, I have a base class: class ContentItem(models.Model): title = models.CharField(max_length=1000) page_order = models.IntegerField() last_update_date = models.DateTimeField(default=datetime.now()) cl...


class - Why do attribute references act like this with Python inheritance?

This question already has answers here:


python properties and inheritance

I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like: class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:


Python inheritance - how to disable a function

In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?


python - Single Table Inheritance in Django

Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good ...


multiple inheritance - Why can't I inherit from dict AND Exception in Python?

I got the following class : class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(...


inheritance - Python super() raises TypeError

In Python 2.5, the following code raises a TypeError: &gt;&gt;&gt; class X: def a(self): print "a" &gt;&gt;&gt; class Y(X): def a(self): super(Y,self).a() print "b" &gt;&gt;&gt; c = Y() &gt;&gt;&gt; c.a() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in a TypeError: super() argument 1 mu...


inheritance - Validating Python Arguments in Subclasses

I'm trying to validate a few python arguments. Until we get the new static typing in Python 3.0, what is the best way of going about this. Here is an example of what I am attempting: class A(object): @accepts(int, int, int) def __init__(a, b, c): pass class B(A): @accepts(int, int, int, int) def __init__(a, b, c, d): A.__init__(a, b, c) As you can s...


Inheritance and Overriding __init__ in python

I was reading 'Dive Into Python' and in the chapter on classes it gives this example: class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename The author then says that if you want to override the __init__ method, you must explicitly call the parent __init__ with the ...


python - Discussion of multiple inheritance vs Composition for a project (+other things)

I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors. The example below briefly demonstrates the concept. #prewritten class Sensor(object): def __init__(self): print "Hello from Sensor" #...


inheritance - Python base class method call: unexpected behavior

Why does str(A()) seemingly call A.__repr__() and not dict.__str__() in the example below? class A(dict): def __repr__(self): return 'repr(A)' def __str__(self): return dict.__str__(self) class B(dict): def __str__(self): return dict.__str__(self) print 'call: repr(A) expect: repr(A) get:', repr(A()) # works print 'call: str(A)...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top