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?

3
  • 1
    You can use a descriptor, e.g. property Commented Oct 13, 2020 at 10:28
  • you cannot call a class method like that unless you use decorators. f.val will return the address of that method object in the class as follows, <bound method Foo_class.val of <__main__.Foo_class object at 0x000002A1D9098160>> Commented Oct 13, 2020 at 10:30
  • 1
    You can also just do self.val = x in the __init__... ;) Commented Oct 13, 2020 at 10:38

1 Answer 1

4
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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 do you like my detailed explanation :)?
It is surely better than a code-only answer, but see the answers in the linked duplicate to see what is detailed explanation :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.