How do I properly use a function under a class?What is the purpose of __str__ and __repr__?How to merge two dictionaries in a single expression?How do I check if a list is empty?Are Static class variables possible on Python?How do I check whether a file exists without exceptions?How to flush output of print function?How can I safely create a nested directory?Using global variables in a functionHow do I sort a dictionary by value?How to make a chain of function decorators?How do I list all files of a directory?

What is the most suitable position for a bishop here?

Why don't we have a weaning party like Avraham did?

What does this Swiss black on yellow rectangular traffic sign with a symbol looking like a dart mean?

A word for delight at someone else's failure?

Justifying Affordable Bespoke Spaceships

What are the current battlegrounds for people’s “rights” in the UK?

What is the highest voltage from the power supply a Raspberry Pi 3 B can handle without getting damaged?

King or Queen-Which piece is which?

What is the oldest commercial MS-DOS program that can run on modern versions of Windows without third-party software?

Subtract the Folded Matrix

Find All Possible Unique Combinations of Letters in a Word

Counterfeit checks were created for my account. How does this type of fraud work?

What are Elsa's reasons for selecting the Holy Grail on behalf of Donovan?

Extending prime numbers digit by digit while retaining primality

Can I change normal plug to a 15amp round pin plug?

How much steel armor can you wear and still be able to swim?

What constitutes a syllable?

Should I include an appendix for inessential, yet related worldbuilding to my story?

Rejecting an offer after accepting it just 10 days from date of joining

How many people are necessary to maintain modern civilisation?

Designing a magic-compatible polearm

Can you use one creature for both convoke and delve for Hogaak?

Drawing a second weapon as part of an attack?

Can the pre-order traversal of two different trees be the same even though they are different?



How do I properly use a function under a class?


What is the purpose of __str__ and __repr__?How to merge two dictionaries in a single expression?How do I check if a list is empty?Are Static class variables possible on Python?How do I check whether a file exists without exceptions?How to flush output of print function?How can I safely create a nested directory?Using global variables in a functionHow do I sort a dictionary by value?How to make a chain of function decorators?How do I list all files of a directory?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








9















I am currently learning Python. Since I am a big fan of OO (object-oriented) programming, obviously it's not hard to apply it in Python. But when I tried it, it seems very different to C#.



As you can see below, I am trying to create a character class, with three attributes Id, Hp, and Mana. The score is calculated by adding up Hp and Mana and then times 10.



As you can see, after defining MyChar where id=10 hp=100 mana=100, I was expecting MyChar.Score is (100+100)*10, which is 2000, but weirdly, it says:



bound method Character.Score of <__main__.Character object at 0x0000021B17DD1F60> as the result of print(MyChar.Score).



How can I fix this problem?



Here is my code:



class Character:

def __init__(self, Id, Hp, Mana):
self.Id = Id;
self.Hp = Hp;
self.Mana = Mana;


def Score(self):
return (self.Hp + self.Mana)*10;

MyChar = Character(10, 100, 100);

print(MyChar.Score)









share|improve this question









New contributor



FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.














  • 5





    Score is not an attribute but a member function, invoke it like print(MyChar.Score())

    – Kunal Mukherjee
    Jun 11 at 11:23






  • 1





    @Kunal It could be, though. This is especially useful when passing functions/methods into higher-order functions such as map/filter. :)

    – TrebledJ
    Jun 11 at 11:28







  • 4





    I would swear that this kind of functions are also called methods and are invoked with () in C#.

    – Goyo
    Jun 11 at 11:30






  • 2





    @KunalMukherjee yes it is - the MyChar.Score() expression first resolves the "Score" attribute on MyChar object (yielding a method object), then applies the call operator (the parens) on it.

    – bruno desthuilliers
    Jun 11 at 11:30






  • 1





    @Goyo you may want to read this about what Python "methods" really are: wiki.python.org/moin/FromFunctionToMethod - as a general rule, Python's object model is wildly different from C#'s one, so while you'll find the same basic concepts of class, instance, attribute, method etc, you won't have a 1:1 mapping with the way C# implement those concepts.

    – bruno desthuilliers
    Jun 11 at 11:33

















9















I am currently learning Python. Since I am a big fan of OO (object-oriented) programming, obviously it's not hard to apply it in Python. But when I tried it, it seems very different to C#.



As you can see below, I am trying to create a character class, with three attributes Id, Hp, and Mana. The score is calculated by adding up Hp and Mana and then times 10.



As you can see, after defining MyChar where id=10 hp=100 mana=100, I was expecting MyChar.Score is (100+100)*10, which is 2000, but weirdly, it says:



bound method Character.Score of <__main__.Character object at 0x0000021B17DD1F60> as the result of print(MyChar.Score).



How can I fix this problem?



Here is my code:



class Character:

def __init__(self, Id, Hp, Mana):
self.Id = Id;
self.Hp = Hp;
self.Mana = Mana;


def Score(self):
return (self.Hp + self.Mana)*10;

MyChar = Character(10, 100, 100);

print(MyChar.Score)









share|improve this question









New contributor



FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.














  • 5





    Score is not an attribute but a member function, invoke it like print(MyChar.Score())

    – Kunal Mukherjee
    Jun 11 at 11:23






  • 1





    @Kunal It could be, though. This is especially useful when passing functions/methods into higher-order functions such as map/filter. :)

    – TrebledJ
    Jun 11 at 11:28







  • 4





    I would swear that this kind of functions are also called methods and are invoked with () in C#.

    – Goyo
    Jun 11 at 11:30






  • 2





    @KunalMukherjee yes it is - the MyChar.Score() expression first resolves the "Score" attribute on MyChar object (yielding a method object), then applies the call operator (the parens) on it.

    – bruno desthuilliers
    Jun 11 at 11:30






  • 1





    @Goyo you may want to read this about what Python "methods" really are: wiki.python.org/moin/FromFunctionToMethod - as a general rule, Python's object model is wildly different from C#'s one, so while you'll find the same basic concepts of class, instance, attribute, method etc, you won't have a 1:1 mapping with the way C# implement those concepts.

    – bruno desthuilliers
    Jun 11 at 11:33













9












9








9








I am currently learning Python. Since I am a big fan of OO (object-oriented) programming, obviously it's not hard to apply it in Python. But when I tried it, it seems very different to C#.



As you can see below, I am trying to create a character class, with three attributes Id, Hp, and Mana. The score is calculated by adding up Hp and Mana and then times 10.



As you can see, after defining MyChar where id=10 hp=100 mana=100, I was expecting MyChar.Score is (100+100)*10, which is 2000, but weirdly, it says:



bound method Character.Score of <__main__.Character object at 0x0000021B17DD1F60> as the result of print(MyChar.Score).



How can I fix this problem?



Here is my code:



class Character:

def __init__(self, Id, Hp, Mana):
self.Id = Id;
self.Hp = Hp;
self.Mana = Mana;


def Score(self):
return (self.Hp + self.Mana)*10;

MyChar = Character(10, 100, 100);

print(MyChar.Score)









share|improve this question









New contributor



FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I am currently learning Python. Since I am a big fan of OO (object-oriented) programming, obviously it's not hard to apply it in Python. But when I tried it, it seems very different to C#.



As you can see below, I am trying to create a character class, with three attributes Id, Hp, and Mana. The score is calculated by adding up Hp and Mana and then times 10.



As you can see, after defining MyChar where id=10 hp=100 mana=100, I was expecting MyChar.Score is (100+100)*10, which is 2000, but weirdly, it says:



bound method Character.Score of <__main__.Character object at 0x0000021B17DD1F60> as the result of print(MyChar.Score).



How can I fix this problem?



Here is my code:



class Character:

def __init__(self, Id, Hp, Mana):
self.Id = Id;
self.Hp = Hp;
self.Mana = Mana;


def Score(self):
return (self.Hp + self.Mana)*10;

MyChar = Character(10, 100, 100);

print(MyChar.Score)






python python-3.x






share|improve this question









New contributor



FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited Jun 12 at 0:07









Peter Mortensen

14.2k1988114




14.2k1988114






New contributor



FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked Jun 11 at 11:19









FrankWFrankW

725




725




New contributor



FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




FrankW is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









  • 5





    Score is not an attribute but a member function, invoke it like print(MyChar.Score())

    – Kunal Mukherjee
    Jun 11 at 11:23






  • 1





    @Kunal It could be, though. This is especially useful when passing functions/methods into higher-order functions such as map/filter. :)

    – TrebledJ
    Jun 11 at 11:28







  • 4





    I would swear that this kind of functions are also called methods and are invoked with () in C#.

    – Goyo
    Jun 11 at 11:30






  • 2





    @KunalMukherjee yes it is - the MyChar.Score() expression first resolves the "Score" attribute on MyChar object (yielding a method object), then applies the call operator (the parens) on it.

    – bruno desthuilliers
    Jun 11 at 11:30






  • 1





    @Goyo you may want to read this about what Python "methods" really are: wiki.python.org/moin/FromFunctionToMethod - as a general rule, Python's object model is wildly different from C#'s one, so while you'll find the same basic concepts of class, instance, attribute, method etc, you won't have a 1:1 mapping with the way C# implement those concepts.

    – bruno desthuilliers
    Jun 11 at 11:33












  • 5





    Score is not an attribute but a member function, invoke it like print(MyChar.Score())

    – Kunal Mukherjee
    Jun 11 at 11:23






  • 1





    @Kunal It could be, though. This is especially useful when passing functions/methods into higher-order functions such as map/filter. :)

    – TrebledJ
    Jun 11 at 11:28







  • 4





    I would swear that this kind of functions are also called methods and are invoked with () in C#.

    – Goyo
    Jun 11 at 11:30






  • 2





    @KunalMukherjee yes it is - the MyChar.Score() expression first resolves the "Score" attribute on MyChar object (yielding a method object), then applies the call operator (the parens) on it.

    – bruno desthuilliers
    Jun 11 at 11:30






  • 1





    @Goyo you may want to read this about what Python "methods" really are: wiki.python.org/moin/FromFunctionToMethod - as a general rule, Python's object model is wildly different from C#'s one, so while you'll find the same basic concepts of class, instance, attribute, method etc, you won't have a 1:1 mapping with the way C# implement those concepts.

    – bruno desthuilliers
    Jun 11 at 11:33







5




5





Score is not an attribute but a member function, invoke it like print(MyChar.Score())

– Kunal Mukherjee
Jun 11 at 11:23





Score is not an attribute but a member function, invoke it like print(MyChar.Score())

– Kunal Mukherjee
Jun 11 at 11:23




1




1





@Kunal It could be, though. This is especially useful when passing functions/methods into higher-order functions such as map/filter. :)

– TrebledJ
Jun 11 at 11:28






@Kunal It could be, though. This is especially useful when passing functions/methods into higher-order functions such as map/filter. :)

– TrebledJ
Jun 11 at 11:28





4




4





I would swear that this kind of functions are also called methods and are invoked with () in C#.

– Goyo
Jun 11 at 11:30





I would swear that this kind of functions are also called methods and are invoked with () in C#.

– Goyo
Jun 11 at 11:30




2




2





@KunalMukherjee yes it is - the MyChar.Score() expression first resolves the "Score" attribute on MyChar object (yielding a method object), then applies the call operator (the parens) on it.

– bruno desthuilliers
Jun 11 at 11:30





@KunalMukherjee yes it is - the MyChar.Score() expression first resolves the "Score" attribute on MyChar object (yielding a method object), then applies the call operator (the parens) on it.

– bruno desthuilliers
Jun 11 at 11:30




1




1





@Goyo you may want to read this about what Python "methods" really are: wiki.python.org/moin/FromFunctionToMethod - as a general rule, Python's object model is wildly different from C#'s one, so while you'll find the same basic concepts of class, instance, attribute, method etc, you won't have a 1:1 mapping with the way C# implement those concepts.

– bruno desthuilliers
Jun 11 at 11:33





@Goyo you may want to read this about what Python "methods" really are: wiki.python.org/moin/FromFunctionToMethod - as a general rule, Python's object model is wildly different from C#'s one, so while you'll find the same basic concepts of class, instance, attribute, method etc, you won't have a 1:1 mapping with the way C# implement those concepts.

– bruno desthuilliers
Jun 11 at 11:33












4 Answers
4






active

oldest

votes


















20














If you want to use it like a property in C#, decorate the function with @property, like so:



class Character:

def __init__(self,Id,Hp,Mana):
self.Id=Id;
self.Hp=Hp;
self.Mana=Mana;

@property
def Score(self):
return (self.Hp+self.Mana)*10;

MyChar=Character(10,100,100);

print(MyChar.Score)


So you don't have to call it like a function.



For more advanced usage of properties (e.g. also having a setter func), see the official docs: https://docs.python.org/3/library/functions.html#property






share|improve this answer




















  • 5





    While that's a nice suggestion, it doesn't really answer the OP's question.

    – bruno desthuilliers
    Jun 11 at 11:38











  • @brunodesthuilliers I don't understand. This adds a single line (the decorator) to OP's example and fixes the problem. How does this not answer the question?

    – Teepeemm
    Jun 12 at 3:25






  • 1





    @Teepeemm The OP asked why the expression MyChar.Score didn't eval to the return value of the Score method, not how to make it a computed attribute instead of a method.

    – bruno desthuilliers
    Jun 12 at 6:58







  • 1





    While the title does ask how to use the function, the body simply asks "How can I fix this problem?" It seems that either MyChar.Score() or @property def Score cause the print statement to work as OP wanted, and this approach has the advantage of encapsulating more logic into the class definition.

    – Teepeemm
    Jun 12 at 11:34






  • 1





    Wow, that's exactly what I'm looking for! Thank you so much!

    – FrankW
    Jun 13 at 7:07


















19














tl;dr



Use it like any other function by calling it: print(MyChar.Score()) (note the additional pair of parentheses).




As you've correctly stated, MyChar.Score is a "function under a class" (aka "method"). So just use it like any other function by calling it: suffixing it with a pair of parentheses.



print(MyChar.Score())
# ^^


Without the call, simply doing print(MyChar.Score) prints <bound method blah blah>, i.e. the informal string representation of the method. The print function internally calls __str__() magic method (or __repr__(), if the former isn't defined). Hence, the following print equivalent lines:



print(MyChar.Score.__str__())
print(str(MyChar.Score))
print(MyChar.Score.__repr__())
print(repr(MyChar.Score))


In Python, functions are first-class citizens, hence they are objects and have the __str__() and __repr__() methods.






share|improve this answer




















  • 7





    Without the parentheses, you were not calling the function. Instead, you were printing a representation of the function itself, which is a method of the character class called 'Score'.

    – Deepstop
    Jun 11 at 11:25


















7














In Python, everything is an object, including classes, functions and methods, so MyChar.Score (without the parens) only resolves the Score attribute on MyChar object. This yields a method object, which happens to be a callable object (an object that implements the __call__ special method). You then have to apply the call operator (the parens) to actually call it.



You may want to check the official documentation for more on Python's object model.






share|improve this answer






























    0














    class Character(object):
    def __init__(self):
    print ('Starting')

    def method(self):
    print ('This is a method()')
    ch = Character()


    '''When we dont add the bracket after the method call it would lead to method bound error as in your case'''
    print (ch.method)
    '''This can be solved by doing the following line'''
    ch.method()





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );






      FrankW is a new contributor. Be nice, and check out our Code of Conduct.









      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56542562%2fhow-do-i-properly-use-a-function-under-a-class%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      20














      If you want to use it like a property in C#, decorate the function with @property, like so:



      class Character:

      def __init__(self,Id,Hp,Mana):
      self.Id=Id;
      self.Hp=Hp;
      self.Mana=Mana;

      @property
      def Score(self):
      return (self.Hp+self.Mana)*10;

      MyChar=Character(10,100,100);

      print(MyChar.Score)


      So you don't have to call it like a function.



      For more advanced usage of properties (e.g. also having a setter func), see the official docs: https://docs.python.org/3/library/functions.html#property






      share|improve this answer




















      • 5





        While that's a nice suggestion, it doesn't really answer the OP's question.

        – bruno desthuilliers
        Jun 11 at 11:38











      • @brunodesthuilliers I don't understand. This adds a single line (the decorator) to OP's example and fixes the problem. How does this not answer the question?

        – Teepeemm
        Jun 12 at 3:25






      • 1





        @Teepeemm The OP asked why the expression MyChar.Score didn't eval to the return value of the Score method, not how to make it a computed attribute instead of a method.

        – bruno desthuilliers
        Jun 12 at 6:58







      • 1





        While the title does ask how to use the function, the body simply asks "How can I fix this problem?" It seems that either MyChar.Score() or @property def Score cause the print statement to work as OP wanted, and this approach has the advantage of encapsulating more logic into the class definition.

        – Teepeemm
        Jun 12 at 11:34






      • 1





        Wow, that's exactly what I'm looking for! Thank you so much!

        – FrankW
        Jun 13 at 7:07















      20














      If you want to use it like a property in C#, decorate the function with @property, like so:



      class Character:

      def __init__(self,Id,Hp,Mana):
      self.Id=Id;
      self.Hp=Hp;
      self.Mana=Mana;

      @property
      def Score(self):
      return (self.Hp+self.Mana)*10;

      MyChar=Character(10,100,100);

      print(MyChar.Score)


      So you don't have to call it like a function.



      For more advanced usage of properties (e.g. also having a setter func), see the official docs: https://docs.python.org/3/library/functions.html#property






      share|improve this answer




















      • 5





        While that's a nice suggestion, it doesn't really answer the OP's question.

        – bruno desthuilliers
        Jun 11 at 11:38











      • @brunodesthuilliers I don't understand. This adds a single line (the decorator) to OP's example and fixes the problem. How does this not answer the question?

        – Teepeemm
        Jun 12 at 3:25






      • 1





        @Teepeemm The OP asked why the expression MyChar.Score didn't eval to the return value of the Score method, not how to make it a computed attribute instead of a method.

        – bruno desthuilliers
        Jun 12 at 6:58







      • 1





        While the title does ask how to use the function, the body simply asks "How can I fix this problem?" It seems that either MyChar.Score() or @property def Score cause the print statement to work as OP wanted, and this approach has the advantage of encapsulating more logic into the class definition.

        – Teepeemm
        Jun 12 at 11:34






      • 1





        Wow, that's exactly what I'm looking for! Thank you so much!

        – FrankW
        Jun 13 at 7:07













      20












      20








      20







      If you want to use it like a property in C#, decorate the function with @property, like so:



      class Character:

      def __init__(self,Id,Hp,Mana):
      self.Id=Id;
      self.Hp=Hp;
      self.Mana=Mana;

      @property
      def Score(self):
      return (self.Hp+self.Mana)*10;

      MyChar=Character(10,100,100);

      print(MyChar.Score)


      So you don't have to call it like a function.



      For more advanced usage of properties (e.g. also having a setter func), see the official docs: https://docs.python.org/3/library/functions.html#property






      share|improve this answer















      If you want to use it like a property in C#, decorate the function with @property, like so:



      class Character:

      def __init__(self,Id,Hp,Mana):
      self.Id=Id;
      self.Hp=Hp;
      self.Mana=Mana;

      @property
      def Score(self):
      return (self.Hp+self.Mana)*10;

      MyChar=Character(10,100,100);

      print(MyChar.Score)


      So you don't have to call it like a function.



      For more advanced usage of properties (e.g. also having a setter func), see the official docs: https://docs.python.org/3/library/functions.html#property







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jun 11 at 12:11









      Radeonx

      508




      508










      answered Jun 11 at 11:25









      Adam.Er8Adam.Er8

      1,283414




      1,283414







      • 5





        While that's a nice suggestion, it doesn't really answer the OP's question.

        – bruno desthuilliers
        Jun 11 at 11:38











      • @brunodesthuilliers I don't understand. This adds a single line (the decorator) to OP's example and fixes the problem. How does this not answer the question?

        – Teepeemm
        Jun 12 at 3:25






      • 1





        @Teepeemm The OP asked why the expression MyChar.Score didn't eval to the return value of the Score method, not how to make it a computed attribute instead of a method.

        – bruno desthuilliers
        Jun 12 at 6:58







      • 1





        While the title does ask how to use the function, the body simply asks "How can I fix this problem?" It seems that either MyChar.Score() or @property def Score cause the print statement to work as OP wanted, and this approach has the advantage of encapsulating more logic into the class definition.

        – Teepeemm
        Jun 12 at 11:34






      • 1





        Wow, that's exactly what I'm looking for! Thank you so much!

        – FrankW
        Jun 13 at 7:07












      • 5





        While that's a nice suggestion, it doesn't really answer the OP's question.

        – bruno desthuilliers
        Jun 11 at 11:38











      • @brunodesthuilliers I don't understand. This adds a single line (the decorator) to OP's example and fixes the problem. How does this not answer the question?

        – Teepeemm
        Jun 12 at 3:25






      • 1





        @Teepeemm The OP asked why the expression MyChar.Score didn't eval to the return value of the Score method, not how to make it a computed attribute instead of a method.

        – bruno desthuilliers
        Jun 12 at 6:58







      • 1





        While the title does ask how to use the function, the body simply asks "How can I fix this problem?" It seems that either MyChar.Score() or @property def Score cause the print statement to work as OP wanted, and this approach has the advantage of encapsulating more logic into the class definition.

        – Teepeemm
        Jun 12 at 11:34






      • 1





        Wow, that's exactly what I'm looking for! Thank you so much!

        – FrankW
        Jun 13 at 7:07







      5




      5





      While that's a nice suggestion, it doesn't really answer the OP's question.

      – bruno desthuilliers
      Jun 11 at 11:38





      While that's a nice suggestion, it doesn't really answer the OP's question.

      – bruno desthuilliers
      Jun 11 at 11:38













      @brunodesthuilliers I don't understand. This adds a single line (the decorator) to OP's example and fixes the problem. How does this not answer the question?

      – Teepeemm
      Jun 12 at 3:25





      @brunodesthuilliers I don't understand. This adds a single line (the decorator) to OP's example and fixes the problem. How does this not answer the question?

      – Teepeemm
      Jun 12 at 3:25




      1




      1





      @Teepeemm The OP asked why the expression MyChar.Score didn't eval to the return value of the Score method, not how to make it a computed attribute instead of a method.

      – bruno desthuilliers
      Jun 12 at 6:58






      @Teepeemm The OP asked why the expression MyChar.Score didn't eval to the return value of the Score method, not how to make it a computed attribute instead of a method.

      – bruno desthuilliers
      Jun 12 at 6:58





      1




      1





      While the title does ask how to use the function, the body simply asks "How can I fix this problem?" It seems that either MyChar.Score() or @property def Score cause the print statement to work as OP wanted, and this approach has the advantage of encapsulating more logic into the class definition.

      – Teepeemm
      Jun 12 at 11:34





      While the title does ask how to use the function, the body simply asks "How can I fix this problem?" It seems that either MyChar.Score() or @property def Score cause the print statement to work as OP wanted, and this approach has the advantage of encapsulating more logic into the class definition.

      – Teepeemm
      Jun 12 at 11:34




      1




      1





      Wow, that's exactly what I'm looking for! Thank you so much!

      – FrankW
      Jun 13 at 7:07





      Wow, that's exactly what I'm looking for! Thank you so much!

      – FrankW
      Jun 13 at 7:07













      19














      tl;dr



      Use it like any other function by calling it: print(MyChar.Score()) (note the additional pair of parentheses).




      As you've correctly stated, MyChar.Score is a "function under a class" (aka "method"). So just use it like any other function by calling it: suffixing it with a pair of parentheses.



      print(MyChar.Score())
      # ^^


      Without the call, simply doing print(MyChar.Score) prints <bound method blah blah>, i.e. the informal string representation of the method. The print function internally calls __str__() magic method (or __repr__(), if the former isn't defined). Hence, the following print equivalent lines:



      print(MyChar.Score.__str__())
      print(str(MyChar.Score))
      print(MyChar.Score.__repr__())
      print(repr(MyChar.Score))


      In Python, functions are first-class citizens, hence they are objects and have the __str__() and __repr__() methods.






      share|improve this answer




















      • 7





        Without the parentheses, you were not calling the function. Instead, you were printing a representation of the function itself, which is a method of the character class called 'Score'.

        – Deepstop
        Jun 11 at 11:25















      19














      tl;dr



      Use it like any other function by calling it: print(MyChar.Score()) (note the additional pair of parentheses).




      As you've correctly stated, MyChar.Score is a "function under a class" (aka "method"). So just use it like any other function by calling it: suffixing it with a pair of parentheses.



      print(MyChar.Score())
      # ^^


      Without the call, simply doing print(MyChar.Score) prints <bound method blah blah>, i.e. the informal string representation of the method. The print function internally calls __str__() magic method (or __repr__(), if the former isn't defined). Hence, the following print equivalent lines:



      print(MyChar.Score.__str__())
      print(str(MyChar.Score))
      print(MyChar.Score.__repr__())
      print(repr(MyChar.Score))


      In Python, functions are first-class citizens, hence they are objects and have the __str__() and __repr__() methods.






      share|improve this answer




















      • 7





        Without the parentheses, you were not calling the function. Instead, you were printing a representation of the function itself, which is a method of the character class called 'Score'.

        – Deepstop
        Jun 11 at 11:25













      19












      19








      19







      tl;dr



      Use it like any other function by calling it: print(MyChar.Score()) (note the additional pair of parentheses).




      As you've correctly stated, MyChar.Score is a "function under a class" (aka "method"). So just use it like any other function by calling it: suffixing it with a pair of parentheses.



      print(MyChar.Score())
      # ^^


      Without the call, simply doing print(MyChar.Score) prints <bound method blah blah>, i.e. the informal string representation of the method. The print function internally calls __str__() magic method (or __repr__(), if the former isn't defined). Hence, the following print equivalent lines:



      print(MyChar.Score.__str__())
      print(str(MyChar.Score))
      print(MyChar.Score.__repr__())
      print(repr(MyChar.Score))


      In Python, functions are first-class citizens, hence they are objects and have the __str__() and __repr__() methods.






      share|improve this answer















      tl;dr



      Use it like any other function by calling it: print(MyChar.Score()) (note the additional pair of parentheses).




      As you've correctly stated, MyChar.Score is a "function under a class" (aka "method"). So just use it like any other function by calling it: suffixing it with a pair of parentheses.



      print(MyChar.Score())
      # ^^


      Without the call, simply doing print(MyChar.Score) prints <bound method blah blah>, i.e. the informal string representation of the method. The print function internally calls __str__() magic method (or __repr__(), if the former isn't defined). Hence, the following print equivalent lines:



      print(MyChar.Score.__str__())
      print(str(MyChar.Score))
      print(MyChar.Score.__repr__())
      print(repr(MyChar.Score))


      In Python, functions are first-class citizens, hence they are objects and have the __str__() and __repr__() methods.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jun 12 at 5:14

























      answered Jun 11 at 11:22









      TrebledJTrebledJ

      5,33441435




      5,33441435







      • 7





        Without the parentheses, you were not calling the function. Instead, you were printing a representation of the function itself, which is a method of the character class called 'Score'.

        – Deepstop
        Jun 11 at 11:25












      • 7





        Without the parentheses, you were not calling the function. Instead, you were printing a representation of the function itself, which is a method of the character class called 'Score'.

        – Deepstop
        Jun 11 at 11:25







      7




      7





      Without the parentheses, you were not calling the function. Instead, you were printing a representation of the function itself, which is a method of the character class called 'Score'.

      – Deepstop
      Jun 11 at 11:25





      Without the parentheses, you were not calling the function. Instead, you were printing a representation of the function itself, which is a method of the character class called 'Score'.

      – Deepstop
      Jun 11 at 11:25











      7














      In Python, everything is an object, including classes, functions and methods, so MyChar.Score (without the parens) only resolves the Score attribute on MyChar object. This yields a method object, which happens to be a callable object (an object that implements the __call__ special method). You then have to apply the call operator (the parens) to actually call it.



      You may want to check the official documentation for more on Python's object model.






      share|improve this answer



























        7














        In Python, everything is an object, including classes, functions and methods, so MyChar.Score (without the parens) only resolves the Score attribute on MyChar object. This yields a method object, which happens to be a callable object (an object that implements the __call__ special method). You then have to apply the call operator (the parens) to actually call it.



        You may want to check the official documentation for more on Python's object model.






        share|improve this answer

























          7












          7








          7







          In Python, everything is an object, including classes, functions and methods, so MyChar.Score (without the parens) only resolves the Score attribute on MyChar object. This yields a method object, which happens to be a callable object (an object that implements the __call__ special method). You then have to apply the call operator (the parens) to actually call it.



          You may want to check the official documentation for more on Python's object model.






          share|improve this answer













          In Python, everything is an object, including classes, functions and methods, so MyChar.Score (without the parens) only resolves the Score attribute on MyChar object. This yields a method object, which happens to be a callable object (an object that implements the __call__ special method). You then have to apply the call operator (the parens) to actually call it.



          You may want to check the official documentation for more on Python's object model.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jun 11 at 11:38









          bruno desthuilliersbruno desthuilliers

          53.4k54766




          53.4k54766





















              0














              class Character(object):
              def __init__(self):
              print ('Starting')

              def method(self):
              print ('This is a method()')
              ch = Character()


              '''When we dont add the bracket after the method call it would lead to method bound error as in your case'''
              print (ch.method)
              '''This can be solved by doing the following line'''
              ch.method()





              share|improve this answer





























                0














                class Character(object):
                def __init__(self):
                print ('Starting')

                def method(self):
                print ('This is a method()')
                ch = Character()


                '''When we dont add the bracket after the method call it would lead to method bound error as in your case'''
                print (ch.method)
                '''This can be solved by doing the following line'''
                ch.method()





                share|improve this answer



























                  0












                  0








                  0







                  class Character(object):
                  def __init__(self):
                  print ('Starting')

                  def method(self):
                  print ('This is a method()')
                  ch = Character()


                  '''When we dont add the bracket after the method call it would lead to method bound error as in your case'''
                  print (ch.method)
                  '''This can be solved by doing the following line'''
                  ch.method()





                  share|improve this answer















                  class Character(object):
                  def __init__(self):
                  print ('Starting')

                  def method(self):
                  print ('This is a method()')
                  ch = Character()


                  '''When we dont add the bracket after the method call it would lead to method bound error as in your case'''
                  print (ch.method)
                  '''This can be solved by doing the following line'''
                  ch.method()






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jun 11 at 11:54

























                  answered Jun 11 at 11:47









                  Saurav RaiSaurav Rai

                  1777




                  1777




















                      FrankW is a new contributor. Be nice, and check out our Code of Conduct.









                      draft saved

                      draft discarded


















                      FrankW is a new contributor. Be nice, and check out our Code of Conduct.












                      FrankW is a new contributor. Be nice, and check out our Code of Conduct.











                      FrankW is a new contributor. Be nice, and check out our Code of Conduct.














                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56542562%2fhow-do-i-properly-use-a-function-under-a-class%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form