[Tutor] method, type?

Peter Otten __peter__ at web.de
Wed Jan 6 03:19:07 EST 2016


Alex Kleider wrote:

> #!/usr/bin/env python3
> # OS: Ubuntu 10.4LTS
> 
> # My code:
> 
> class JournalLineItem(object):
>      """
>      """
> 
>      def __init__(self, account, debit_or_credit, amount):
>          self.account = account
>          self.debit_or_credit = debit_or_credit
>          self.amount = float(amount)
> 
>      def show(self):
>          return ("ACNT: {}  ${:0.2f} {}".
>              format(self.account, self.amount, self.debit_or_credit))
> 
>      def get_line_item(text):
>          return JournalLineItem(*text.split())
> 
> def test():
>      print(
>      JournalLineItem.get_line_item("2435 Dr 25.33").show())
> 
> if __name__ == "__main__":
>      test()
> 
>      myquestion = """
> What kind of a method/function is get_line_item?

Let's see:

>>> class Class:
...     def method(*args): print("args passed:", args)
... 
>>> Class.method
<function Class.method at 0x7fea4219b510>
>>> Class.method(42)
args passed: (42,)

When you call it

Class.method(...)

in Python 3 method is just an ordinary function (in Python 2 it was an 
"unbound method").

>>> inst = Class()
>>> inst.method
<bound method Class.method of <__main__.Class object at 0x7fea421a9828>>
>>> inst.method(42)
args passed: (<__main__.Class object at 0x7fea421a9828>, 42)

When you call it

inst = Class(...)
inst.method(...)

method is a "bound method", i. e. it implicitly adds inst as the first 
argument. Therefore

item = JournalLineItem(...)
item.get_line_text(text) # function gets two args

will fail. As your get_line_item() is actually and "alternative constructor" 
you should make it a class method for it to pass the actual class as the 
first argument with both instances and the class.

@classmethod
def get_line_item(cls, text):
    return cls(*text.split())

When you use that argument to create the instances subclasses then will 
automatically create subclass instances, i. e.

class Modified(JournalLineItem):
   pass

assert isinstance(Modified.get_line_text(...), Modified)

Finally a little table:

invoked with | @staticmethod  | @classmethod    | no decorator
------------------------------------------------------------------
class        | args unchanged | class as 1st arg | args unchanged
instance     | args unchanged | class as 1st arg | inst as 1st arg




More information about the Tutor mailing list