1

Given this basic example, but in reality it's more complex: (Name of the file is TestFile)

class Example:
    def test1():
        print("First test")
    def test2():
        print("Second test")
    def test3():
        #Call test1()
        #Call test2()

I've tried Example.test1() and Example.test2(), which works, but if someone would do

from TestFile import Example as MagicTrick

Wouldn't the final function break?

13steinj
  • 427
  • 2
  • 9
  • 16
  • Possible duplicate of: http://stackoverflow.com/questions/5615648/python-call-function-within-class for more details please refer docs https://docs.python.org/2/tutorial/classes.html – Pavan Gupta Aug 05 '15 at 05:41

4 Answers4

1

In reality, you would typically call self.test1() in order to call the method on an instance.

To explicitly show what @BrenBarn said:

class Example:
    def test1():
        print("First test")
    def test2():
        print("Second test")
    def test3(self):
        self.test1()
        self.test2()
The Brofessor
  • 1,008
  • 6
  • 15
0

No, it won't break because of that sort of import. Using as to import something under a different name only affects what it's called in the place where it's imported. In your original file TestFile, the class will still be called Example and can still refer to itself as such. In other words, using as in the import just creates a "local alias"; it doesn't change any other names the imported object might have referring to it.

In reality, you would typically call self.test1() in order to call the method on an instance. That won't work for your example because you didn't provide a self argument, but perhaps that was an oversight in your "basic" example.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
0

The code will work anyway because functions remember where to look for global names.

In Python every function object contains a reference to the global context in which it was defined (the attribute was renamed when passing from Python 2.x to Python 3.x):

# Python 2
def foo(): pass
print foo.func_globals['foo'] is foo  # --> True

# Python 3
def foo(): pass
print(foo.__globals__['foo'] is foo)  # --> True

This context is where the global names are looked up during the execution of the function code, no matter from where the call is coming from.

So while it's true that Example will not exist as a global in the context you're calling methods of MagicTrick from, it will defined during the execution of a method of that class (independently from the fact that you found the class using a different name and looking it up in a different context).

6502
  • 112,025
  • 15
  • 165
  • 265
-1

I would save the call as an object and then use that inside test3

def test1(): Print ...

def test2(): Print ...

A= test1()

B= test2()

def test3():

A

B

ARW
  • 61
  • 2
  • 11