나는 PHP 또는 Java의 가상 메소드를 알고있다.파이썬에서 가상 메소드를 구현하는 방법은 무엇입니까?
어떻게 파이썬으로 구현할 수 있습니까?
또는 추상 클래스에서 빈 메서드를 정의하고 재정의해야합니까?
나는 PHP 또는 Java의 가상 메소드를 알고있다.파이썬에서 가상 메소드를 구현하는 방법은 무엇입니까?
어떻게 파이썬으로 구현할 수 있습니까?
또는 추상 클래스에서 빈 메서드를 정의하고 재정의해야합니까?
물론, 기본 클래스에 메서드를 정의 할 필요조차 없습니다. 파이썬에서 타이핑하는 것은 오리 유형이기 때문에 파이썬 메소드는 가상보다 낫습니다.
class Dog:
def say(self):
print "hau"
class Cat:
def say(self):
print "meow"
pet = Dog()
pet.say() # prints "hau"
another_pet = Cat()
another_pet.say() # prints "meow"
my_pets = [pet, another_pet]
for a_pet in my_pets:
a_pet.say()
Cat
Dog
도이 동작을 할 수 있도록 공통 기본 클래스에서 파생 필요가 없습니다 - 당신은 무료로 얻을 수 있습니다. 즉, 일부 프로그래머는 더 엄격한 방식으로 클래스 계층 구조를 정의하여 더 잘 문서화하고
일부 엄격한 입력을 선호합니다. 가능합니다 (예 :
abc
standard module 참조).
파이썬 메서드는 항상 가상입니다.
사실, 버전 2.6 파이썬은 STH 추상 기본이라는 클래스를 제공하고 명시 적으로 다음과 같이 가상 방법을 설정할 수 있습니다
from abc import ABCMeta
from abc import abstractmethod
...
class C:
__metaclass__ = ABCMeta
@abstractmethod
def my_abstract_method(self, ...):
이 작동 아주 잘, 클래스가 이미 메타 클래스를 사용하는 클래스로부터 상속하지 않습니다 제공 .
파이썬 방법이 항상 이그나시오 같은
가상 있습니다 아직 어떻게 든 클래스 상속 당신이 원하는 것을 구현하는 더 나은 방법 일 수있다.
class Animal:
def __init__(self,name,legs):
self.name = name
self.legs = legs
def getLegs(self):
return "{0} has {1} legs".format(self.name, self.legs)
def says(self):
return "I am an unknown animal"
class Dog(Animal): # <Dog inherits from Animal here (all methods as well)
def says(self): # <Called instead of Animal says method
return "I am a dog named {0}".format(self.name)
def somethingOnlyADogCanDo(self):
return "be loyal"
formless = Animal("Animal", 0)
rover = Dog("Rover", 4) #<calls initialization method from animal
print(formless.says()) # <calls animal say method
print(rover.says()) #<calls Dog says method
print(rover.getLegs()) #<calls getLegs method from animal class
결과는 다음과 같아야합니다
I am an unknown animal
I am a dog named Rover
Rover has 4 legs
NotImplementedError
는 메소드를 구현하지 않는다 "추상적"기본 클래스의 "순수 가상 방법"에 올리는 권장되는 예외입니다.
다른 사람들이 말했듯이 이것은 대부분 문서화 규칙이며 필수는 아니지만 누락 된 속성 오류보다 의미있는 예외가 발생합니다.
https://docs.python.org/3.5/library/exceptions.html#NotImplementedError는 말한다 :
이 예외는
RuntimeError
에서 파생됩니다. 사용자 정의 기본 클래스에서 파생 클래스가 메서드를 재정의해야 할 때 추상 메서드는이 예외를 발생시켜야합니다.
예 ::
class Base(object):
def virtualMethod(self):
raise NotImplementedError()
def usesVirtualMethod(self):
return self.virtualMethod() + 1
class Derived(Base):
def virtualMethod(self):
return 1
print Derived().usesVirtualMethod()
Base().usesVirtualMethod()
을 제공합니다
2
Traceback (most recent call last):
File "./a.py", line 13, in <module>
Base().usesVirtualMethod()
File "./a.py", line 6, in usesVirtualMethod
return self.virtualMethod() + 1
File "./a.py", line 4, in virtualMethod
raise NotImplementedError()
NotImplementedError
파이썬 방법은 항상 가상입니다.
... 개인 정보 보호는 제공되지 않습니다. C++ 녀석에게는 너무 나빴어.
'cat.say()'는'another_pet.say()'여야합니다. – dusan
@ dusan : 감사합니다. 결정된. 예를 들어 –
+1 개들은 어떤 언어로 "hau"라고 말합니까? – JeremyP