phpでは、以下の様に変数にプロパティ名を代入して、オブジェクトのプロパティの値を取得することができます。
php
1<?php 2class Test { 3 public $textProperty; 4 function Test($textValue) { 5 $this->textProperty = $textValue; 6 } 7} 8$inst = new Test('テキスト'); 9$propertyName = 'textProperty'; 10printf('%s'."\n", $inst->$propertyName); 11?>
このような記述をPythonで実施することはできますでしょうか?
私の浅いPythonの経験と知識では、以下の様なリフレクション的な記述で値を取得することぐらいしか思いつきません。
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from sys import stdout class Test: textProperty = None def __init__(self, textValue): self.textProperty = textValue def main(): inst = Test('テキスト') propertyName = 'textProperty' stdout.write('%s\n' % getattr(inst, propertyName)) if(__name__ == '__main__'):main()
このPythonのコードをphpに直すと以下のようになると思います。
php
1<?php 2class Test { 3 public $textProperty; 4 function Test($textValue) { 5 $this->textProperty = $textValue; 6 } 7} 8$inst = new Test('テキスト'); 9$propertyName = 'textProperty'; 10printf('%s'."\n", $inst->__get($propertyName)); 11?>
このようなリフレクション的な記述ではなく、最初のphpの記述のように、コードベース(=関数等を使わない)で値を取得するようなコードの記述は、Pythonで可能でしょうか?
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/08/25 00:12