0

For example, I have an instance:

class Job(object):
    def __init__(self, name, client=None):
        self.name = name
        self.client = client

job = Job('test')

job.client  # I don't want the client to be accessed outside, as it's only as an internal attribute.

from searching in the community, I didn't find a solution I want.

Although I knew that setting client as __client could achieve this, I don't want to change the attribute name.

I guess some magic functions are able to achieve this, like __dict__ or __getattr__. can someone show me some idea? very appreciate.

DennisLi
  • 3,915
  • 6
  • 30
  • 66
  • You can use the @property decorator https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes – andrralv Apr 30 '20 at 02:10
  • Python does not have private variables. You can use a *single* underscore to denote that something is not part of the public API – juanpa.arrivillaga Apr 30 '20 at 02:22
  • @andrralv no, `property` doesn't really prevent anything from being accessible. – juanpa.arrivillaga Apr 30 '20 at 02:24
  • @juanpa.arrivillaga Yes, I know that way, but I prefer using magic function and I think Python can achieve it with magic function. – DennisLi Apr 30 '20 at 02:35
  • Why? Python *doesn't have private variables*. Why do you want to go against the conventional/recommended way? There is no way (other than by writing a C-extension) to make a variable inaccessible – juanpa.arrivillaga Apr 30 '20 at 02:38
  • alright, I think override `__getattr__` can do this, but it's in a hack way. – DennisLi Apr 30 '20 at 03:11
  • Overwriting `__getattr__` will only hide **one** way to access an attribute. It will not make it inaccessible. – Klaus D. Apr 30 '20 at 03:32
  • @KlausD. yes, that's what I want. I want to hide it, the same effect as prefix `__` way. – DennisLi Apr 30 '20 at 04:14

0 Answers0