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 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名