0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonのクラスキャストの方法

Last updated at Posted at 2016-09-02

結論

 出来ない。
 やり方知ってる方がいれば、教えて欲しい。

クラスキャストとは?

マンガでわかるjava入門講座がわかりやすいと思いました。

pythonで本当に出来ないの?

実際にGoogle先生に問い合わせるとpythonで
クラスキャスト実現してみようとしている人は、いるみたいです。

Pythonでクラスのキャストとか

よくよく見てみるとクラスキャストではなく
クラスのattrをコピーしているだけで、
キャストになっていないように見えます。

例えば。。。

お試し

def cast(ChildClass, parental_obj):
    child_obj = ChildClass()
    for attr_name in parental_obj.__dict__:
        setattr(child_obj, attr_name, getattr(parental_obj, attr_name))
    return child_obj


class ParentalClass():
    parental_attr = "parental"

class ChildClass(ParentalClass):
    child_attr = ""

child_object = ChildClass()
child_object.child_attr = "child_attr"


parental_object = cast(ParentalClass, child_object)
print(parental_object.parental_attr)
print(parental_object.child_attr)

親クラスに"キャスト"した後に、
子クラスのchild_attrにアクセスできてしまうのは、
おかしいですね。

javaで同じことを行うと、
エラーになりますよね。

SuperClass
public class SuperClass {
	public SuperClass() {
		// TODO Auto-generated constructor stub
	}
}
SubClass
public class SubClass extends SuperClass {

    public String name = "SubClass";

	public SubClass() {
		// TODO Auto-generated constructor stub
	}
}
main
public class main {

    public static void main(String[] args) {
		// TODO Auto-generated method stub
        // SubClass生成
        SubClass subClass = new SubClass();
        // SuperClassにキャスト
        SuperClass superClass = subClass;
        // SubClassのnameにアクセス
        System.out.println(superClass.name); //⇦ここでエラー
    }
}

SubClassを生成して、SuperClassにキャストした後に
SubClassのメンバー変数のnameにアクセスするとエラーが発生します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?