Python 3 의 대상 과 클래스
8054 단어 Python
클래스 정의 클래스 사용 하기
class Person():
pass #pass 는 빈 클래스 class Person():definit__(self,name): self.name=name hunter=Person('Elmer Fud')print(hunter.name)계승,덮어 쓰기,새로운 방법 추가
# _*_ coding: utf-8_*_
class Car():
def exclaim(self):
print("I'm a Car! ")
class Yugo(Car): #
def exclaim(self): #
print("I'm a Yugo!")
def need_a_push(self): #
print("A little help here?")
give_me_a_car = Car()
give_me_a_yugo = Yugo()
give_me_a_car.exclaim()
give_me_a_yugo.exclaim()
give_me_a_yugo.need_a_push()
D:\MyPython>python test2.py
I'm a Car!
I'm a Yugo!
A little help here?
슈퍼 를 사용 하여 부모 클래스 에서 도움 을 받 습 니 다.
class Person():
def __init__(self, name):
self.name = name
class EmailPerson(Person):
def __init__(self, name, email):
super().__init__(name) # super() Person
self.email = email
bob = EmailPerson('Bob Frapples', '[email protected]')
print(bob.name)
print(bob.email)
D:\MyPython>python test2.py Bob Frapples
[email protected]
속성(property)을 사용 하여 특성(attribute)에 접근 하고 설정 합 니 다.
# _*_ coding: utf-8_*_
class Duck():
def __init__(self, input_name):
self.hidden_name = input_name
def get_name(self):
print('inside the getter')
return self.hidden_name
def set_name(self, input_name):
print('inside the setter')
self.hidden_name = input_name
name = property(get_name, set_name)
fowl = Duck('Howard')
print(fowl.name) # name ,get_name()
fowl.get_name() #
fowl.name = 'Daffy' # name ,set_name()
fowl.set_name('Daffy')
D:\MyPython>python test2.py inside the getter
Howard
inside the getter
inside the setter
inside the setter
속성 을 정의 하 는 방식 도 사용 할 수 있 습 니 다:장식 기
@property,getter 방법 지시 에 사용
@name.setter,setter 방법 표시 에 사용
# _*_ coding: utf-8_*_
class Duck():
def __init__(self, input_name):
self.hidden_name = input_name
@property
def name(self):
print('inside the getter')
return self.hidden_name
@name.setter
def name(self, input_name):
print('inside the setter')
self.hidden_name = input_name
fowl = Duck('Howard')
print(fowl.name)
fowl.name = 'Daffy'
print(fowl.name)
D:\MyPython>python test2.py inside the getter
Howard
inside the setter
inside the getter
Daffy
name 속성 지향 클래스 에 저 장 된 특정한 특성 을 사용 하 는 것 외 에 계산 결과 값 도 가리 킬 수 있 습 니 다.
# _*_ coding: utf-8_*_
class Circle():
def __init__(self, radius):
self.radius = radius
@property
def diameter(self):
return 2 * self.radius
c = Circle(5)
print(c.radius)
print(c.diameter)
c.radius = 7
print(c.diameter)
D:\MyPython>python test2.py 5 10 14
이름 을 사용 하여 개인 특성 을 재정 비 합 니 다.
hidden 을name 을 로 변경name(밑줄 두 개 로 시작)
# _*_ coding: utf-8_*_
class Duck():
def __init__(self, input_name):
self.__name = input_name
@property
def name(self):
print('inside the getter')
return self.__name
@name.setter
def name(self, input_name):
print('inside the setter')
self.__name = input_name
fowl = Duck('Howard')
print(fowl.name)
fowl.name = 'Daffy'
print(fowl.name)
print(fowl.__name) # , fowl._Duck__name
D:\MyPython>python test2.py inside the getter Howard inside the setter inside the getter Daffy Traceback (most recent call last): File "test2.py", line 18, in print(fowl.__name) AttributeError: 'Duck' object has no attribute '__name'
방법의 유형:(인 스 턴 스 방법,클래스 방법,정적 방법)
# _*_ coding: utf-8_*_
class A():
count = 0
def __init__(self): # self
A.count += 1
def exclaim(self):
print("I'm an A!")
@classmethod #
def kids(cls): #cls
print("A has", cls.count, "little objects.")
easy_a = A()
breezy_a = A()
wheezy_a = A()
A.kids()
D:\MyPython>python test2.py
A has 3 little objects.
정적 방법
오리 종류
# _*_ coding: utf-8_*_
class CoyoteWeapon():
@staticmethod
def commercial():
print('This CoyoyeWeapon has been brought to you')
CoyoteWeapon.commercial() #
D:\MyPython>python test2.py Elemer Fudd says: I'm hunting wabbits. Bugs Bunny says: What's up, doc? Daffy Duck says: It's rabbit season! Elemer Fudd says I'm hunting wabbits. Bugs Bunny says What's up, doc? Daffy Duck says It's rabbit season! Brook says Babble
특수 방법 또는 큐 브 방정식(special method):더 블 밑줄()시작 과 끝
# _*_ coding: utf-8_*_
class Quote():
def __init__(self, person, words):
self.person = person
self.words = words
def who(self):
return self.person
def says(self):
return self.words + '.'
class QuestionQuote(Quote): #
def says(self):
return self.words + '?'
class ExclamationQuote(Quote):
def says(self):
return self.words + '!'
#
hunter = Quote('Elemer Fudd', "I'm hunting wabbits")
print(hunter.who(), 'says:', hunter.says())
hunter1 = QuestionQuote('Bugs Bunny', "What's up, doc")
print(hunter1.who(),'says:', hunter1.says())
hunter2 = ExclamationQuote('Daffy Duck',"It's rabbit season")
print(hunter2.who(), 'says:', hunter2.says())
#Python , who() says(), , (duck typing)
class BabblingBrook():
def who(self):
return 'Brook'
def says(self):
return 'Babble'
brook = BabblingBrook()
def who_says(obj):
print(obj.who(),'says', obj.says())
who_says(hunter)
who_says(hunter1)
who_says(hunter2)
who_says(brook)
D:\MyPython>python test2.py True False True False
# _*_ coding: utf-8_*_
#Python , who() says(), , (duck typing)
class Word():
def __init__(self, text):
self.text = text
def equals(self, word2):
return self.text.lower() == word2.text.lower() #self.text Word
first = Word('ha')
second = Word('HA')
third = Word('en')
print(first.equals(second))
print(first.equals(third))
class Word2():
def __init__(self, text):
self.text = text
def __eq__(self, word2):
return self.text.lower() == word2.text.lower()
first = Word2('ha')
second = Word2('HA')
third = Word2('en')
print(first == second)
print(first == third)
조합
모듈 이 아 닌 클래스 와 대상 을 언제 사용 합 니까?
비슷 한 행동 이 많이 필요 하지만 서로 다른 상태의 인 스 턴 스 가 필요 할 때 대상 을 사용 합 니 다.클래스 는 계승 을 지원 하고 모듈 은 지원 하지 않 습 니 다.모듈 은 인 스 턴 스 의 유일 성 을 확보 할 수 있 습 니 다.모듈 이 프로그램 에서 몇 번 인용 되 든 하나의 인 스 턴 스 만 불 러 옵 니 다.만약 에 여러 개의 가치 변 수 를 포함 하고 그들 이 매개 변수 로 서로 다른 함수 에 들 어 갈 수 있다 면 그들 을 클래스 에 밀봉 하 는 것 이 좋 습 니 다.가장 간단 한 방법 으로 문 제 를 해결 하고 사전 을 사용 하 며 목록 과 원 조 는 모듈 을 사용 하 는 것 보다 간단 하고 간결 하 며 사용 류 는 더욱 복잡 하 다.
원본 그룹 이름:
1.명칭;2:여러 도 메 인 이름 으로 구 성 된 문자열 입 니 다.각 도 메 인 이름 사 이 는 빈 칸 으로 구분 되 어 있 으 며,nametuple 함수 로 만 들 수 있 습 니 다.
장점:가 변 적 이지 않 은 대상 과 매우 비슷 하 다.사용 대상 에 비해 이름 을 가 진 원 조 를 사용 하 는 것 이 시간 과 공간 적 으로 효율 적 입 니 다.사전 의 키 로 사용 할 수 있 습 니 다.사전 스타일 의 괄호 대신 점(.)을 사용 하여 특성 에 접근 할 수 있 습 니 다.
__eq__(self, other) self == other
__ne__(self, other) self != other
__lt__(self, other) self < other
__gt__(self, other) self > other
__le__(self, other) self <= other
__ge__(self, other) self >= other
__add__(self, other) self + other
__sub__(self, other) self - other
__mul__(self, other) self * other
__floordiv__(self, other) self // other
__truediv__(self, other) self / other
__mov__(self, other) self % other
__pow__(self, other) self ** other
__str__(self) str(self)
__repr__(self) repr(self) #
__len__(self) len(self)
본 고 는 제 가 정가 리 의 을 배 웠 고 공부 에 만 사 용 했 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python의 None과 NULL의 차이점 상세 정보그래서 대상 = 속성 + 방법 (사실 방법도 하나의 속성, 데이터 속성과 구별되는 호출 가능한 속성 같은 속성과 방법을 가진 대상을 클래스, 즉 Classl로 분류할 수 있다.클래스는 하나의 청사진과 같아서 하나의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.