logo
down
shadow

Connect to a Class Method by it's method name holded into a var in a for loop in python


Connect to a Class Method by it's method name holded into a var in a for loop in python

By : Jimmy.zhuang
Date : November 22 2020, 03:01 PM
With these it helps I don't know the OperationsRig class definition, so I define one by myself.
Since it could successfully match, I think it is not the problem of pyqt.
code :
class OperationsRig:
    def foo(self, msg):
        print('foo:' + str(msg))
        return 'foo OK'

    def foo1(self, msg):
        print('foo1:' + str(msg))
        return 'foo1 OK'


opr = OperationsRig()

def operations_module(text):
    # Text gives me the name to Match ------------------#
    # ------------------------#
    # have 3 ways of getting the class instance methods into a list to iterate ..
    method_list = [func for func in dir(opr) if callable(getattr(opr, func))]

    # This var is a list to pass to the Method
    Sel_list = [1,2,3]

    # iterate over the "self.OperationsRig" methods
    #
    """ option 1 """
    for meth in method_list:
        if text.strip().lower() in meth.lower()[:]:
            # if match, and it does, will call the class method and send the data.
            pass
            return getattr(opr, meth)(Sel_list)  # Executes the funcion instance, but is not
                                                         # sending the data, I've checked printing inside.
                                                         # NoneTypeObject is not iterable. no data sent.
print(operations_module('foo'))
print(operations_module('foo1'))
foo:[1, 2, 3]
foo OK
foo1:[1, 2, 3]
foo1 OK

Process finished with exit code 0


Share : facebook icon twitter icon
How to distinguish an instance method, a class method, a static method or a function in Python 3?

How to distinguish an instance method, a class method, a static method or a function in Python 3?


By : Praphul Dn
Date : March 29 2020, 07:55 AM
will help you You just need to get the type of the method, but since methods are descriptors, you have to :
1 - Get the class out of the instance. 2 - Look up the method reference in __dict__ instead of making an attribute lookup.
code :
>>> f = Foo()
>>> type(f.__class__.__dict__['bari'])
<class 'function'>
>>> type(f.__class__.__dict__['barc'])
<class 'classmethod'>
>>> type(f.__class__.__dict__['bars'])
<class 'staticmethod'>
Besides instance method, static method, and class method, is there a fourth type of method in Python?

Besides instance method, static method, and class method, is there a fourth type of method in Python?


By : jess
Date : March 29 2020, 07:55 AM
I wish did fix the issue. This is still a regular instance method. You can demonstrate this like so:
code :
>>> class Foo:
        mystery_method(*args, **kwargs):
            print(*args, sep = '\n')
>>> f = Foo(1, 'bar', None)
>>> f.mystery_method()
<__main__.Foo object at XXXX>
1
bar
None
Breaking a while loop from other method inside the same class in Python

Breaking a while loop from other method inside the same class in Python


By : Matias
Date : March 29 2020, 07:55 AM
seems to work fine a.start() is an infinite loop. Since nothing runs at the same time, it just runs and never reaches the next statements.
You need to create a thread, like this
code :
import time,threading

class example():

    def __init__(self):
        self.__recording = False

    def start(self):
        self.__recording = True
        while self.__recording:
            time.sleep(1)
            print(1)

    def stop(self):
        self.__recording = False

a = example()
t = threading.Thread(target=a.start)
t.start()
time.sleep(5)
a.stop()
t.join()
import time,threading

class example(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self,target=self.run)

        self.__recording = False

    def run(self):
        self.__recording = True
        while self.__recording:
            time.sleep(1)
            print(1)

    def join(self):
        self.__recording = False
        threading.Thread.join(self)

a = example()
a.start()
time.sleep(5)
a.join()
Python call class method from iterable value in for loop

Python call class method from iterable value in for loop


By : adam
Date : March 29 2020, 07:55 AM
hope this fix your issue Say have a simple class as follows: , You can use the getattr Python method, to call methods by name:
code :
class Test:

    def first_method(self):
        print("1")

    def second_method(self):
        print("2")


test = Test()

methods=['first_method', 'second_method']

for method in methods:
    getattr(test, method)()
Why don't Python class method decorators receive the method as a bound method?

Why don't Python class method decorators receive the method as a bound method?


By : Gherman
Date : March 29 2020, 07:55 AM
I hope this helps . This is impossible; you'd have to use a class decorator or metaclass instead. Decorator syntax
Related Posts Related Posts :
  • django how to use Max and Count on the same field in back-to-back annotations
  • Using the OR operator seems to only take the first of two conditions when used with np.where filter
  • Elegant Dataframe Operations in Pandas
  • Change metadata of pdf file with pypdf2
  • How can I animate a set of points with matplotlib?
  • error: (-215) count >= 0 && (depth == CV_32F || depth == CV_32S) in function arcLength
  • OpenStack KeyStone SSL Exception When Creating an Instance of KeyStone
  • pyspark: The system cannot find the path specified
  • How can I set path to load data from CSV file into PostgreSQL database in Docker container?
  • Summation in python dictionary
  • DRF 3.7.0 removed handling None in fields and broke my foreign key source fields. Is there a way around it?
  • Error with Padlen in signal.filtfilt in Python
  • Abstract matrix multiplication with variables
  • Reading binary data on bit level
  • How to replace multiple instances of a sub strings in a string using a for loop (in a function)?
  • py2neo cypher create several relations to central node in for loop
  • [python-3]TypeError: must be str, not int
  • How to exit/terminate a job earlier and handle the raised exception in apscheduler?
  • python, print intermediate values while loop
  • python to loop over yaml config
  • D3.js is not recognized by PyCharm
  • Access the regularization paths obtained from ElasticNetCV in sklearn
  • Pattern table to Pandas DataFrame
  • Get the earliest date from a column (Python Pandas) after csv.reader
  • Get SystemError: Parent module '' not loaded, cannot perform relative import when trying to import numpy in a Cython Ext
  • Bash or Python : Append and prepend a string recursively in all .tex files
  • Changing a certain index of boolean list of lists change others, too
  • complex dataframe filtering request on the last occurence of a value in Panda/Python [EDIT]
  • How to repeatedly get the contents of a Text widget every loop with tkinter?
  • How to call the tornado.queues message externally
  • How can I use regex in python so that characters not included are disallowed?
  • Discarding randmly scattered empty spaces in pandas data frame
  • Get sums grouped by date by same column filtered by 2 conditions
  • Element disappears when I add an {% include %} tag inside my for loop
  • Django Rest Framework with either a slug or a pk lookup field for the DetailAPIView
  • Flask doesn't stream on Lambda
  • Generate all permutations of fixed length where the elements come from two different sets
  • Making function for calculating distance
  • How to handle multiprocessing based on the limit of CPU's
  • Django - static files is not working
  • Remove x axis and y axis black lines with matplotlib
  • tkinter: assigning multiple functions to one button
  • flask-jwt-extended: Fake Authorization Header during testing (pytest)
  • Setting pandas dataframe value based on row and column conditions
  • swig char ** as a pointer to a char *
  • Confusion over `a` and `b` attributes from scipy.stats.uniform
  • How can I do groupy.apply() without sort my index?
  • Querying Google Cloud datastore with ancestor not returning anything
  • Read value from one thread in Python: queue or global variable?
  • Django - context process query being repeated 102 times
  • Convert a list of images and labels to np array to train tensorflow
  • Lambda not supporting NLTK file size
  • Numpy ndarray image pixel mean for pixel values greater than zero: Normalizing image
  • Understanding output of np.corrcoef for two matrices of different sizes
  • Finding longest perfect match between two strings
  • what is wrong with my cosine similarity? Tensorflow
  • How to manage user content in django?
  • Receiving unsupported operand error while comparing random number and user input.
  • How to wrap the process of creating start_urls in scrapy?
  • How to mark 'duplicated sequence' in pandas?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org