Do you use the get/set pattern (in Python)?

后端 未结 8 1969
长情又很酷
长情又很酷 2020-12-12 13:25

Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this.

Why do you use or avoid get/set methods in Py

8条回答
  •  Happy的楠姐
    2020-12-12 14:13

    Your observation is correct. This is not a normal style of Python programming. Attributes are all public, so you just access (get, set, delete) them as you would with attributes of any object that has them (not just classes or instances). It's easy to tell when Java programmers learn Python because their Python code looks like Java using Python syntax!

    I definitely agree with all previous posters, especially @Maximiliano's link to Phillip's famous article and @Max's suggestion that anything more complex than the standard way of setting (and getting) class and instance attributes is to use Properties (or Descriptors to generalize even more) to customize the getting and setting of attributes! (This includes being able to add your own customized versions of private, protected, friend, or whatever policy you want if you desire something other than public.)

    As an interesting demo, in Core Python Programming (chapter 13, section 13.16), I came up with an example of using descriptors to store attributes to disk instead of in memory!! Yes, it's an odd form of persistent storage, but it does show you an example of what is possible!

    Here's another related post that you may find useful as well: Python: multiple properties, one setter/getter

提交回复
热议问题