简体   繁体   中英

How can I reference another class instance variable when getting or setting another?

Everyone says to use self.variable_name but that only works inside the method that gets or sets it. I need to be able to use the values of other variables set in the instance when setting one.

class WebSite:

    def __init__(self, url='', subdomain='www'):
        self.url = url
        self.subdomain = subdomain

    @property
    def url(self):
        return self.__url

    @url.setter
    def url(self, url):
        self.__url = f'http://{self.subdomain}.example.com'

    @property
    def subdomain(self):
        return self.__subdomain

    @subdomain.setter
    def subdomain(self, subdomain):
        self.__subdomain = subdomain

then:

>>>import package as p
>>>site = p.website()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/dblack/Code/package/package/website.py", line 4, in __init__
    self.url = url
  File "/Users/dblack/Code/package/package/website.py", line 13, in url
    self.__url = f'http://{self.subdomain}.site.com'
  File "/Users/dblack/Code/package/package/website.py", line 17, in subdomain
    return self.__subdomain
AttributeError: 'WebSite' object has no attribute '_WebSite__subdomain'

I tried a lot of finagling, this must be the wrong approach completely.

It is certainly possible, but your code has inter-related dependencies. Setting the url property looks up self.subdomain , which calls the subdomain property which in turn looks up the value of self.__subdomain - which doesn't exist yet.

You should at least set self.subdomain first. However, you should reconsider having getters and setters for subdomain at all; just set the an attribute directly. Either way, you should avoid the double-underscore prefix, since this does name mangling and leads to behaviour you may not expect; if you must set a hidden attribute, use a single underscore prefix.

A number of issues.

  • You define a class member url as a property, and an instance member url as a variable. Instance members shadow class members at lookup.
  • You access .__url instance member without creating it first, in the constructor.
  • You define a trivial getter and a trivial setter for a private variable .__url . It makes no sense . If you want a world-writable value, just use a variable; Python is not Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM