0

OOP noob here.. But.. is it possible to call a function after a function. I don't know how to describe it, so I'll ask it with an example:

class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.email = ''

    def set_email(self, email):
        self.email = email

    def print_email(self):
        print("You email is: {}".format(self.email))

    def with_name(self):
        print("Your name is {} and email is {}".format(self.name, self.email))

subject = Human("Bucky", 24)
subject.set_email("bucky@gmail.com")
subject.print_email().with_name()   # Doubt here

Is it possible to call a function after .print_email() such as .with_name() so that the email gets printed with name and the print function in the .print_email() function doesn't gets printed at all??

Saw this type of thing in Javascript, was thinking that is it possible here in python?

Nitish
  • 392
  • 2
  • 7
  • Yes it is possible, but the function needs to return something, that has the method you're calling on it. – Dschoni Jan 20 '21 at 11:55
  • That's called function / method chaining and is not related to the programming language. It only requires a programming language with OOP. Here is a tutorial: https://www.tutorialspoint.com/Explain-Python-class-method-chaining – Thomas Sablik Jan 20 '21 at 11:56
  • Wait, why would you want to do that? `print_email(with_name=True)` is better in Python. – user202729 Jan 20 '21 at 11:56
  • 1
    btw, with the code you have posted you only need to call: `subject.with_name()`. – quamrana Jan 20 '21 at 11:56
  • Sure, it's *possible*. You would need to design your classes appropriately: they would both need to have a `__str__` method (for converting to a string representation) and would need to return `self` in most of the methods. The [schedule](https://pypi.org/project/schedule/) module uses a calling convention something like that. – larsks Jan 20 '21 at 11:58
  • `Does this answer your question? Fluent interface with Python – quamrana`.Yes this does solves my problem. Only needed to return self. Thankyou very much. – Nitish Jan 20 '21 at 12:03

0 Answers0