0

I hase test class:

class Foo_class:

    def __init__(self,x=0):
        """init, x defaul as 0."""
        self.x=x

    def val(self):
        return self.x

I want to understand, how can call:

f=Foo_class()
print(f.val)

That f.val will return value of def f.val().

Is it possible?

Timur U
  • 415
  • 2
  • 14

1 Answers1

3
class Foo_class:

    def __init__(self,x=0):
        """init, x defaul as 0."""
        self.x=x
        
    @property
    def val(self):
        return self.x

test = Foo_class()
test.val

In case you're wondering what's going on: This is basically a nicer version of getters and setters as java people use them. There if you write a class you're supposed to never expose instance variables but have a method for getting/setting values so you can change what's going on under the hood without breaking code that's working with it. In python exposing things is fine since you can use this.

Lukas S
  • 3,212
  • 2
  • 13
  • 25
  • 2
    Code-only answers are not so helpful - neither for OP nor for future readers - especially in such higher-level material questions. `property` is a special and confusing decorator in Python and some explanations (possibly some links) will greatly improve the answer. Nevertheless, this question is a duplicate and shouldn't be answered anyway... – Tomerikoo Oct 13 '20 at 10:37
  • @Tomerikoo do you like my detailed explanation :)? – Lukas S Oct 18 '20 at 12:09
  • It is surely better than a code-only answer, but see the answers in the linked duplicate to see what is *detailed explanation* :) – Tomerikoo Oct 18 '20 at 13:00