0

I am trying to initialize a class attribute by calling a function. Please see below. This code works as expected meanwhile it makes me confused. To my understanding getmemtoto is a so-called unbound function which need to be called with a instance of class T. How could it be called during the class definition?

class T:
    def getmemtot():
        output=shell(r"sed -r -n -e 's/^MemTotal:\s*([[:digit:]]+)\s*kB/\1/ p' /proc/meminfo")
        return int(output)
    MEMTOT=T.getmemtot()

If I tried to call getmemtot directly I got below errors:

>>> T.getmemtot()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method getmemtot() must be called with T instance as first argument (got nothing instead)
>>> getmemtot()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'getmemtot' is not defined
dproc
  • 63
  • 6

1 Answers1

0

Instead of T.getmemtot() use T().getmemtot(). The difference being T is a class object whereas T() is an instance of the class T.

vielkind
  • 2,840
  • 1
  • 16
  • 16
  • I understand T().getmemtot works since getmemtot is a object method. What is confusing me is why inside the class definition T.getmemtot is callable. – dproc Jul 20 '18 at 05:44
  • You should use `self` instead `T` while working inside the class like `MEMTOT=self.getmemtot()`. It will solve your confusion. – Shameer Kashif Jul 20 '18 at 05:46