OOP:getter/setter方法 [英] OOP: getter/setter methods

查看:86
本文介绍了OOP:getter/setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我读到您应该通过诸如object.get_this()object.set_that(value)之类的getter/setter方法访问对象属性.该代码是否也适用于该类中定义的方法?或仅将它们与对象实例一起使用.例如,以这种方式这样做是惯用的,

So I've read that you're supposed to access object attributes through getter/setter methods like object.get_this() or object.set_that(value). Does this code hold for methods that are also defined within the class? Or they are only meant to be used with object instances. For instance, is it idiomatic to do it this way,

class test:
    def __init__(self,value):
        self.value = value
    def get_value(self):
        return self.value
    def method(self):
        return some_operation(self.value)

定义了

用于访问对象实例的value,还是应该在类方法中使用get_value()?

with get_value() defined for accessing value for an object instance, or should get_value() also be used within class methods?

class test:
    def __init__(self,value):
        self.value = value
    def get_value(self):
        return self.value
    def method(self):
        return some_operation(self.get_value())

推荐答案

在python中属性.

In python do not use getter/setter methods. Instead just access the attribute itself, or, if you need code to be run every time the attribute is accessed or set, use properties.

这篇关于OOP:getter/setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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