N
N
Niriter Inc.2019-11-05 11:37:45
Python
Niriter Inc., 2019-11-05 11:37:45

How to execute multiple methods at one time python?

How can you execute multiple class methods with one line of code?
For example:

class hi():
    def hello(self):
        return str("Hello")

    def world(self, hello_str):
        tmp = hello_str + "World!"
        return tmp

caller = hi()
print(caller.hello().world())

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2019-11-05
@niriter

a couple of ways
If you want the last method to return a result, you can do this:

class Hello(object):
    def __init__(self):
         self.msg = 'Hello'

    def hello(self, world):
        self.msg = self.msg + ', ' + world
        return self

    def print(self):
        return self.msg

caller = Hello()
msg = caller.hello('niriter').print()
print(msg) # Hello, niriter

This kind of code is used in different kinds of builders, when you need to configure an object in different ways for different conditions (different kinds of builders, collect a request in ORM, etc.)
In your library for working with html, this method is used (along with the second one) - you call different kinds methods, but returns the same object with a different state, and you can always call a new method (delete an element, add, delete everything) and, as a result, call getting your desired
class Hello(object):
    def __init__(self, msg='Friend'):
         self.msg = msg

    def print(self):
        init_msg = self.hello()
        return init_msg + ',  ' + self.msg
    
    def hello(self): # этот метод вызываем изнутри другого метода
        return str("Hello")

caller1 = Hello()
print(caller1.print()) # Hello, Friend

caller2 = Hello('Maks')
print(caller2.print()) # Hello, Maks

Encapsulation from the world of OOP, exposes a certain method to the outside, and by calling it, some behavior and state change will be performed. Needed to hide all the details and nuances and leaves only a convenient API for work.
In your library for working with html, this method is used (along with the first one) - it hides complex algorithms for extracting elements, manipulating them, giving back only a convenient API with understandable names

A
asd111, 2019-11-05
@asd111

This is called chaining. This is done using the builder pattern. The bottom line is that each such function returns a copy of the object that called it (or a pointer to it).

class Person: 
   def setName(self, name):
      self.name = name
      return self   ## this is what makes this work

   def setAge(self, age):
      self.age = age;
      return self;

   def setSSN(self, ssn):
      self.ssn = ssn
      return self

p = Person()
p.setName("Hunter")
 .setAge(24)
 .setSSN("111-22-3333")

V
vkulik79, 2019-11-05
@vkulik79

threading module see

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question