나는 클래스 Person
와 2 개의 클래스를 가지고 Child
있으며 Adult
그것은`Person.
class Person:
def __init__(self, name):
self.name = name
self.age = 0
def say_hi(self):
print("Hi, I am " + self.name)
def set_age(self, age):
self.age = age
class Child(Person):
def play_with_children(self):
print("Playing with children")
class Adult(Person):
def drink_alcohol(self):
print("drinking")
인스턴스를 Person
만든 다음 설정 age
하고 이에 따라이 인스턴스가 a Child
또는 Adult
.
또한 그것이 a Child
이고 age
증가한다면 나는 그것이 Adult
. Person
의 생성자 name
가 새 인스턴스를 만들기위한 것이기 때문에이 코드에 오류 가 있습니다.
person1 = Person("Marvin")
person1.set_age(15)
if person1.age < 21:
person1 = Child()# This is an error => expects the name
#But I wouldn't like to handle all members like this => person1 = Child(person1.name)
#I don't want a new instance, is that even posible?
person1.say_hi()
person1.play_with_children()
person1.set_age(25)
if person1.age > 21:
person1 = Adult()# This is an error => expects the name
#But I wouldn't like to handle all members like this => person1 = Adult(person1.name)
#I don't want a new instance, is that even posible?
person1.say_hi()
person1.drink_alcohol()
이것이 가능할까요?
새 인스턴스를 만들지 않고도이 작업을 수행 할 수 있습니까?
추신 : 이것은 내가 가지고있는 더 복잡한 문제의 문제를 보여주는 샘플 코드입니다 (실제로 어린이와 성인이 아닙니다 : D).
주석에서 언급했듯이 Python 3 __class__
에서는 모든 인스턴스에 액세스하여 변경할 수 있습니다.
주의해야하지만이 방법으로 여러 클래스의 속성을 동일한 인스턴스에 추가하고 이상한 괴물을 만들 수 있습니다 (방법은 안전합니다).
person1 = Person("Marvin")
person1.set_age(15)
if person1.age < 21:
person1.__class__ = Child
person1.say_hi()
person1.play_with_children()
person1.set_age(25)
if person1.age > 21:
person1.__class__ = Adult
person1.say_hi()
person1.drink_alcohol()
그래서 괴물 :
class Dog:
def wouf(self):
print("wouf")
person1.__class__ = Dog
print("Attributes are saved, name: "+ person1.name)
#But methods not, so now I can't use person1.say_hi()
person1.wouf()
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다