-2

The initial question I had was whether or not a method could be called from a Python constructor. The answer here suggests that it can, but this surprised me some as, based on my reading, python cannot use something that hasn't been previously defined in the code. Looking at the answers in the linked thread, it seems like they are using a method in the constructor that is defined later in the text. How is this possible in python?

Thanks.

Av06
  • 1
  • 2
  • As long as you don't *call* a function before it is defined (parsed and compiled by Python), you can use it anywhere you like. – meowgoesthedog Apr 02 '19 at 15:40
  • 1
    Without a simple code example it's hard to give a specific answer. But in general the constructor is defined before the methods, but the constructor is *called* after the methods have been defined. – Mark Apr 02 '19 at 15:40
  • 3
    Perhaps this is just a terminology problem. `__init__()` is an _initializer_, not a _constructor_. By the time `__init__()` is called, the object fully exists. – John Gordon Apr 02 '19 at 15:40
  • https://stackoverflow.com/questions/45025005/python-function-calling-order – vi_me Apr 02 '19 at 15:41
  • The actual object constructor is [`__new__`](https://docs.python.org/3/reference/datamodel.html#object.__new__) which amongst other things gives the object its methods, then `__init__` is called to initialize the object. – Jacques Gaudin Apr 02 '19 at 15:43
  • It doesn't "give" an object its methods; methods are created on the fly from the class attribute whose values are functions via the descriptor protocol. As soon as you have an instance, you can try to use its methods. Whether those methods work as intended before the object is initialized is another question. – chepner Apr 02 '19 at 15:45

1 Answers1

0

When you would be running the code the class would be created , the function wouldn't be called

The function would only be called by object in main function by that time the definition of function would be compiled and known.

Try this Declare a class and then call a function which is not a member of class * and also not declared

And declare it later , it would throw an error

Jeffin Sam
  • 98
  • 7