Praktyczny przykład polimorfizmu
Czy ktoś może mi podać prawdziwy, praktyczny przykład polimorfizmu? Mój profesor opowiada mi tę samą starą historię, którą zawsze słyszałem o operatorze +
. a+b = c
i 2+2 = 4
, więc jest to polimorfizm. Naprawdę nie mogę się kojarzyć z taką definicją, ponieważ czytałem i ponownie czytałem to w wielu książkach.
Potrzebuję prawdziwego przykładu z kodem, czegoś, z czym naprawdę mogę się kojarzyć.
Na przykład, oto mały przykład, na wypadek, gdybyś chciał / align = "left" /
>>> class Person(object):
def __init__(self, name):
self.name = name
>>> class Student(Person):
def __init__(self, name, age):
super(Student, self).__init__(name)
self.age = age
3 answers
Sprawdź przykład Wikipedii: jest bardzo pomocny na wysokim poziomie:
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Cat('Mr. Mistoffelees'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
# prints the following:
#
# Missy: Meow!
# Mr. Mistoffelees: Meow!
# Lassie: Woof! Woof!
Zauważ, że wszystkie zwierzęta "mówią", ale mówią inaczej. Zachowanie "mówienia" jest więc polimorficzne w tym sensie, że jest realizowane w różny sposób w zależności od zwierzęcia . Tak więc abstrakcyjne pojęcie " zwierzęce "w rzeczywistości nie" mówi", ale konkretne zwierzęta (jak psy i koty) mają konkretną realizację akcji"talk".
Podobnie operacja "dodaj" jest zdefiniowana w wielu byty matematyczne, ale w szczególnych przypadkach "dodajesz" według określonych reguł: 1+1 = 2, ale (1+2i)+(2-9i)=(3-7i).
Zachowanie polimorficzne pozwala określić wspólne metody na poziomie "abstrakcyjnym" i zaimplementować je w poszczególnych instancjach.
Dla Twojego przykładu:
class Person(object):
def pay_bill():
raise NotImplementedError
class Millionare(Person):
def pay_bill():
print "Here you go! Keep the change!"
class GradStudent(Person):
def pay_bill():
print "Can I owe you ten bucks or do the dishes?"
Widzisz, milionerzy i absolwenci to zarówno osoby. Ale jeśli chodzi o płacenie rachunku, ich konkretne działanie "Zapłać rachunek" jest inne.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-09 14:03:35
Powszechnym prawdziwym przykładem w Pythonie są obiekty podobne do plików . Oprócz rzeczywistych plików, kilka innych typów, w tym StringIO i BytesIO, są podobne do plików. Metoda, która działa jak pliki, może również działać na nich, ponieważ obsługują wymagane metody (np. read
, write
).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-16 06:21:39
Przykład polimorfizmu w C++ z powyższej odpowiedzi brzmiałby:
class Animal {
public:
Animal(const std::string& name) : name_(name) {}
virtual ~Animal() {}
virtual std::string talk() = 0;
std::string name_;
};
class Dog : public Animal {
public:
virtual std::string talk() { return "woof!"; }
};
class Cat : public Animal {
public:
virtual std::string talk() { return "meow!"; }
};
void main() {
Cat c("Miffy");
Dog d("Spot");
// This shows typical inheritance and basic polymorphism, as the objects are typed by definition and cannot change types at runtime.
printf("%s says %s\n", c.name_.c_str(), c.talk().c_str());
printf("%s says %s\n", d.name_.c_str(), d.talk().c_str());
Animal* c2 = new Cat("Miffy"); // polymorph this animal pointer into a cat!
Animal* d2 = new Dog("Spot"); // or a dog!
// This shows full polymorphism as the types are only known at runtime,
// and the execution of the "talk" function has to be determined by
// the runtime type, not by the type definition, and can actually change
// depending on runtime factors (user choice, for example).
printf("%s says %s\n", c2->name_.c_str(), c2->talk().c_str());
printf("%s says %s\n", d2->name_.c_str(), d2->talk().c_str());
// This will not compile as Animal cannot be instanced with an undefined function
Animal c;
Animal* c = new Animal("amby");
// This is fine, however
Animal* a; // hasn't been polymorphed yet, so okay.
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-01 07:46:32