クラスとオブジェクトにプロパティとメソッドを動的に追加
クラスとオブジェクトにプロパティとメソッドを動的に追加
クラスとオブジェクトにプロパティを動的に追加
Personクラスの定義オブジェクトに属性 を追加する.クラスに属性 を追加
クラスとオブジェクトの動的な追加方法動的クラスへの追加方法 オブジェクトへの追加方法
クラスとオブジェクトにプロパティを動的に追加
Personクラスの定義
class Person(object):
def __init__(self, name):
self.name = name
# 2 Person, p1,p2
p1 = Person('amy')
print(p1.name)
p1.age = 10 # p1
print(p1.age) # 10
p2 = Person('anne')
print(p2.name)
p2.age = 18 # p2
print(p2.age) # 18
Person.sex = 'female'
print(p1.sex) # female
print(p2.sex) # female
p2.sex = 'male'
print(p2.sex) # male
クラスとオブジェクトの動的な追加方法
# sleep
def sleep(self):
print('%s sleep' % (self.name))
Person.sleep = sleep
Person.sleep(p1) # amy sleep
Person.sleep(p2) # anne sleep
import types # , types
def eat(self):
print('%s eat' % (self.name))
p.eat = types.MethodType(eat, p) # MethodType() , 1: , 2:
p.eat() # amy eat