Python 3でのgetterとsetterの使い方について、どうすればPythonらしい方法があるのか?

PYTHON3 チュートリアル

Python 3におけるgetterとsetterの使い方

Pythonでは、クラスの属性に対して直接アクセスするのではなく、getterとsetterを使用して属性にアクセスすることが推奨されています。これにより、属性にアクセスする際に追加の処理を行ったり、属性の値を制限したりすることができます。Pythonらしい方法として、プロパティデコレータを使用する方法があります。

プロパティデコレータを使用したgetterとsetterの例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
# インスタンスを作成してgetterとsetterを使用
c = Circle(5)
print(c.radius) # 出力: 5
c.radius = 10
print(c.radius) # 出力: 10
class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): if value < 0: raise ValueError("Radius cannot be negative") self._radius = value # インスタンスを作成してgetterとsetterを使用 c = Circle(5) print(c.radius) # 出力: 5 c.radius = 10 print(c.radius) # 出力: 10
class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("Radius cannot be negative")
        self._radius = value

# インスタンスを作成してgetterとsetterを使用
c = Circle(5)
print(c.radius)  # 出力: 5
c.radius = 10
print(c.radius)  # 出力: 10

上記の例では、Circleクラスにradius属性を持たせて、@propertyデコレータを使ってgetterメソッドを定義し、@radius.setterデコレータを使ってsetterメソッドを定義しています。radius属性にアクセスする際には、実際にはradiusメソッドが呼び出されるため、追加の処理を挟むことができます。

プロパティを使った計算された属性の例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def area(self):
return self._width * self._height
# インスタンスを作成して計算された属性を取得
r = Rectangle(4, 5)
print(r.area) # 出力: 20
class Rectangle: def __init__(self, width, height): self._width = width self._height = height @property def area(self): return self._width * self._height # インスタンスを作成して計算された属性を取得 r = Rectangle(4, 5) print(r.area) # 出力: 20
class Rectangle:
    def __init__(self, width, height):
        self._width = width
        self._height = height

    @property
    def area(self):
        return self._width * self._height

# インスタンスを作成して計算された属性を取得
r = Rectangle(4, 5)
print(r.area)  # 出力: 20

上記の例では、Rectangleクラスにarea属性を持たせて、@propertyデコレータを使ってgetterメソッドを定義しています。area属性はwidthとheightの積を返す計算された属性となっています。

プロパティを使った属性の制限の例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature cannot be below absolute zero")
self._celsius = value
# インスタンスを作成して属性の制限を確認
temp = Temperature(25)
print(temp.celsius) # 出力: 25
temp.celsius = -300 # ValueError: Temperature cannot be below absolute zero
class Temperature: def __init__(self, celsius): self._celsius = celsius @property def celsius(self): return self._celsius @celsius.setter def celsius(self, value): if value < -273.15: raise ValueError("Temperature cannot be below absolute zero") self._celsius = value # インスタンスを作成して属性の制限を確認 temp = Temperature(25) print(temp.celsius) # 出力: 25 temp.celsius = -300 # ValueError: Temperature cannot be below absolute zero
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("Temperature cannot be below absolute zero")
        self._celsius = value

# インスタンスを作成して属性の制限を確認
temp = Temperature(25)
print(temp.celsius)  # 出力: 25
temp.celsius = -300  # ValueError: Temperature cannot be below absolute zero

上記の例では、Temperatureクラスにcelsius属性を持たせて、@propertyデコレータを使ってgetterメソッドとsetterメソッドを定義しています。setterメソッドでは、値が絶対零度未満にならないように制限をかけています。

Python 3では、getterとsetterを使ってクラスの属性にアクセスする方法があります。Pythonらしい方法としては、プロパティ(property)を使うことが推奨されています。

getterとsetterを定義する代わりに、@propertyデコレータを使って属性にアクセスするためのgetterメソッドを定義し、@property_name.setterデコレータを使ってsetterメソッドを定義します。これにより、属性に直接アクセスする代わりに、getterとsetterメソッドを介して属性にアクセスできるようになります。

例えば、以下のようにクラス内でプロパティを定義することができます:

class MyClass:
def __init__(self):
self._my_property = None

@property
def my_property(self):
return self._my_property

@my_property.setter
def my_property(self, value):
self._my_property = value

このようにすることで、my_property属性に対してgetterとsetterを定義し、Pythonらしい方法で属性にアクセスできるようになります。

購読
通知


0 Comments
Inline Feedbacks
View all comments