如何使用get和set方法创建类? [英] How to create a class with get and set methods?

查看:106
本文介绍了如何使用get和set方法创建类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个具有构造函数的myCalc类,该构造函数具有get和set方法并使用一个属性.我了解get和set方法,但是在将所有部分组合在一起时遇到了麻烦,因此它可以执行我想要的操作.到目前为止,我的情况是这样:

I want to create a class myCalc that has a constructor, with get and set methods and uses a property. I understand the get and set methods but am having trouble with putting all of the pieces together so it performs what I want it to do. What I have so far is this:

class myCalc(object):

    def __init__(self):
            self._ =name

        def (self):
            """Get the answer doubled."""
            return self._plus

        def (self):
            """Get the answer squared."""
            return self._times

我想让程序响应的对象具有将对象中的数字加倍和平方的属性.任何建议都会有所帮助.

I'd like to get as far as having the program respond with properties that double and square the number in the object. Any suggestions would be helpful.

推荐答案

属性对象具有getter,setter和deleter方法 您应该使用装饰器,如下所示:

A property object has getter, setter, and deleter methods You should use decorators as follows:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

如果您希望将其设为只读,只需使用@property并删除其他两个

If you want it readonly, just use @property and remove the two others

这篇关于如何使用get和set方法创建类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆