duan7664 2013-04-24 19:35
浏览 91
已采纳

Python 2.7:如何构建getter / setter函数来访问没有继承的类属性?

this is probably a super nub question, apologies. I'm trying to achieve an effect in Python I am familiar with from PHP, which is building getter and setter functions for private attributes.

In PHP I will commonly do something like this:

<?php
class newClass() {
    private $var = null;

    function newClass($initVal) {
        //init
    }

    public function get($var) {
        if ( isset($this->$var) ) {
            return $this->$var;
        }
    }
}
?>

But, trying the same idea in Python:

class newClass():
    def __init__(self, initVal):
        self.__nameOfVar1 = initVal
        self.__nameOfVar2 = initVal


    def get(self, var):
                #assuming, when called, var = nameOfVar1
        if self.__var:
            return self.__var

Throws an error AttributeError:'newClass' object has no attribute '__var'

And quite rightly so, it doesn't. How do I build getter and setter functions to access private attributes?


UPDATE:

I've left the original question because it seems useful for new comers to Python to learn which conventions from other languages they might accidentally be bringing forward. But in reality, my initial problem was a bit different, in attempting to make the problem more general I obfuscated my actual need. So here's an amendment:

In fact I was not working with private attributes; in fact, I am dealing with trying to pass an attribute downward through a composition circumstance. ie:

Class A, as an attribute, has a Class B object that does not inherit from Class A . It is almost never the case that Class B needs any information from Class A, but in my project there is one circumstance where, if a user chooses not provide information to Class B, there is a statement that makes a last-ditch attempt to infer a reasonable solution, but it requires information from Class A that, normally, it never needs.

I could build Class B to always have had that information, but that means that almost always I'm just wasting that time and memory (trivial though it might be). To make this concrete, imagine this:

toothbrush has bristles, and bristles can, provided the user supplies a preferred brushing experience, create a number of bristles appropriate to either a "soft" or a "firm" brush. But, if the user doesn't provide this, then I'd like bristles to ask brush for it's surface area, allowing it to guess what an average number should be.

I came up with this, though I have the intuitive sense that Python programmers will hate me for it; I'd just like to understand why:

@staticmethod
def request(self, var):
    appIndex = self.__dict__
    if appIndex[var]:
        return appIndex[var]

print Class.request(instance, var)

Works like a charm, but I think this is Python heresy. Why?

  • 写回答

2条回答 默认 最新

  • doubiaokai4998 2013-04-24 19:39
    关注

    What you're searching for is properties:

    class Foo():
        def __init__(self):
            self._spam = 0
    
        @property
        def spam(self):
            print("in the getter: ")
            return self._spam
    
        @spam.setter
        def spam(self, move):
            print("in the setter: ")
            self._spam = move + self._spam
    
    f = Foo()
    f.spam = 2
    print(f.spam)
    

    Output:

    in the setter: 
    in the getter: 
    2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算