Return new instance of subclass when using methods inherited from parent class in Python

Return new instance of subclass when using methods inherited from parent class in Python

Content Index :

Return new instance of subclass when using methods inherited from parent class in Python
Tag : python , By : changke
Date : December 01 2020, 04:55 PM

wish helps you In order for arithmetic operators to return an instance of your subclass, you'll have to implement the relevant special methods like __add__, __mul__, __pow__, etc.
The bad news is that there's a lot of those methods. The good news is that you can write code that automatically generates those functions for you. Here's a class decorator that does exactly that:
def add_arithmetic_methods(cls):
    def make_func(func_name):
        def func(self, *args, **kwargs):
            super_method = getattr(super(cls, self), func_name)
            return type(self)(super_method(*args, **kwargs))

        func.__name__ = func_name
        func.__qualname__ = '{}.{}'.format(cls.__qualname__, func_name)
        func.__module__ = cls.__module__

        return func

    for func_name in ['add', 'sub', 'mul', 'matmul', 'truediv', 'floordiv',
                      'mod', 'divmod', 'pow', 'lshift', 'rshift', 'and',
                      'xor', 'or', 'radd', 'rsub', 'rmul', 'rmatmul',
                      'rtruediv', 'rfloordiv', 'rmod', 'rdivmod', 'rpow',
                      'rlshift', 'rrshift', 'rand', 'rxor', 'ror', 'iadd',
                      'isub', 'imul', 'imatmul', 'itruediv', 'ifloordiv',
                      'imod', 'ipow', 'ilshift', 'irshift', 'iand', 'ixor',
                      'ior', 'neg', 'pos', 'abs', 'invert']:
        func_name = '__{}__'.format(func_name)
        func = make_func(func_name)
        setattr(cls, func_name, func)

    return cls
class Phasor(complex):
    def __str__(self):   
        magnitude = (self.real**2 + self.imag**2)**.5
        angle = np.arctan2(self.imag, self.real)
        return "%s ∠ %s°" % (round(magnitude, 2), round(np.degrees(angle), 2))

c = Phasor(3+5j)
# output: 34.0 ∠ 118.07°

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to return new instance of subclass while initializing parent class?

Tag : ruby , By : xie renhui
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , You're breaking a fundamental OO principle here -- classes should know nothing about their subclasses. Of course, sometimes principles should be broken, but there's no apparent reason to do it here.
A far better solution is to shift the instantiation logic to a factory method in a separate class. The factory method takes the same arguments as the A's initializer above, and returns an instance of the appropriate class.

Python subclass not recognizing inherited parent class

Tag : python , By : Jason Haar
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I am struggling with my code, specifically subclasses. I have a parent class that when initialized will call its subclass to be used as an attribute, in the form of a list of objects. I have seen numerous post where a person forgets to call the __init__() of the parent. My issue is different in that the parent is calling the child class and I do not want to call it. , When I run your code, I got the error in the following line:
class subbundle(bundle):
class bundle(object):
    def __init__(self, size,nzone):
        self.size = size
        [ . . .]

class subbundle(bundle):
    """ Defines geometry to represent subbundle"""
    def  __init__(self, row, col, rows,cols):
        [ . . . ]
for i in range (1,self.size):
    subbundle_instance = subbundle(r, c, self.rows, self.cols)

Are subclass properties preserved if I assign a subclass instance to a property typed as a parent class?

Tag : objective-c , By : Ari
Date : March 29 2020, 07:55 AM
hop of those help? If you intend to use methods that are defined in the Status class but not PhotoStatus, you need to check the class of the returned object. To do this, you would normally do something along these lines:
Status *status = viewCommentsViewController.status;
if ([[status class] isSubclassOfClass: [PhotoStatus class]])
    PhotoStatus *photoStatus = (PhotoStatus *) status;
    // Handle photoStatus.
    // Handle the other case.
@implementation Status
- (PhotoStatus *) asPhotoStatus
    return nil;

@implementation PhotoStatus
- (PhotoStatus *) asPhotoStatus
    return self;
[[viewCommentsViewController.status asPhotoStatus] doSomething];

Python class inheritance: dynamic subclass initialization with own and parent defaults and init methods

Tag : python , By : Nougat
Date : March 29 2020, 07:55 AM
hop of those help? You can use the new classmethod added to object() in Python 3.6: __init_subclass__
This method is called when the class is subclassed and allows you to customize the subclasses' creation without using a metaclass.
class Base:
    def __init_subclass__(cls, **kwargs):
        for key, value in kwargs.items():
            setattr(cls, key, value)

    def __init__(self, *args, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)     

class Parent(Base, p_var_1='my_name', p_var_2=2):

class Gen1(Parent, G1_var_1='Generation 1', G1_var_2=[]):

class Gen2(Gen1, G2_var_1=1337, G2_var_2=(10,4)):

Creating a new instance of an inherited class through the inherited static methods

Tag : php , By : brennen
Date : March 29 2020, 07:55 AM
I hope this helps you . I've got a method in my class to create a new 'self' on execution. , Use return new static($id); instead of return new self($id);
Related Posts Related QUESTIONS :
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com