0

Suppose Im creating a class named Bar:

class Bar:
    def __init__(self, foo):
        self.foo = foo

Once I create an object of Bar, How should I get the value of the foo variable?
Should I just type this?

my_class = Bar("Hello")
print(my_class.foo)

Or should I create a method get_foo()?

class Bar:
    def __init__(self, foo):
        self.foo = foo
    def get_foo(self):
        return self.foo

And then write

my_class = Bar("Hello")
print(my_class.get_foo())

First or second option?

BOOM
  • 11
  • 2
  • 1
    First option is for public variables. There's a convention for protected and private variables which is using `_` and `__` as a prefix to the variable respectively. However the 2nd method is not pythonic, the pythonic way is using `@property` on the function which makes it read only. – thethiny Oct 02 '22 at 18:04
  • To add a setter function to it you can then use `@variable.setter`. A good example is this one https://www.programiz.com/python-programming/property – thethiny Oct 02 '22 at 18:06

1 Answers1

0

If you have a class Bar and want to access the variable foo, use your first case that is:

class Bar:
    def __init__(self, foo):
        self.foo = foo

my_class = Bar("Hello")
print(my_class.foo)

But if you want to modify the variable, editing through the object is not recommended. For that, create a function like this:

class Bar:
    def __init__(self, foo):
        self.foo = foo

    def edit_foo(self, newval):
        self.foo = newval
        return self.foo #This is optional, simply for testing

my_class = Bar("Hello")
print(my_class.foo)
print(my_class.edit_foo("Hello World"))
print(my_class.foo)

Now you can edit the variable and also access it with the updated value.

Pycoder
  • 92
  • 9
  • Creating functions just to edit variables is not needed but to show you I created one. Anyways, you wouldn't want to edit everything thru the object but the class would go from one method to another changing the variable values all the time in real world application. – Pycoder Oct 13 '22 at 13:51