Sumedh
Sumedh

Reputation: 648

Why is this working in Python nosetests when logically it should not

class TestUM:

    @classmethod
    def setup_class(will):
        """ Setup Class"""

        will.var = "TEST"

    def setup(this):
        """ Setup """

        print this.var

    def test_number(work):
        """ Method """

        print work.var


    def teardown(orr):
        """ Teardown """

        print orr.var

    @classmethod
    def teardown_class(nott):
        """ Teardown Class """

        print nott.var

Run it as

nosetests -v -s test.py

I am not a Python expert but I cannot figure out why the above code works flawlessly using nose. Every print prints "TEST". What exactly is happening here.

Upvotes: 2

Views: 89

Answers (1)

mhlester
mhlester

Reputation: 23211

In instance methods, the first argument is the instance itself.

In class methods, the first argument is the class itself.

In your case, rather than name that argument self or cls (the convention), you've named it this, work, orr, and nott. But they're all getting the same argument regardless of the name of the argument.

You've successfully set the attribute var to "TEST", so they all see it correctly.


Example functions without the use of classes:

def test1(attribute):
    print attribute

def test2(name):
    print name

def test3(cls):
    print cls

def test4(self):
    print self

Calling those functions:

>>> test1('hello')
hello
>>> test2('hello')
hello
>>> test3('hello')
hello
>>> test4('hello')
hello

The name of the argument doesn't matter. All that matters is what the argument is pointing at, which is always the instance or class

Upvotes: 3

Related Questions