[파이썬 학습]—객체 지향 (9)
1. 사물과의 첫 만남
클래스는 데이터를 기록하는 속성을 정의할 수 있을 뿐만 아니라 행위를 기록하는 함수도 정의할 수 있으며, 클래스에 정의된 속성(변수)을 멤버 변수, 클래스에 정의한 행위(함수)를 멤버 메소드라고 합니다.
멤버 메서드 정의 구문
자기의 역할
- 사물 자체의 의미를 나타냄
- 멤버 메서드는 self를 통해서만 클래스의 멤버 변수에 액세스할 수 있습니다.
- self는 공식 매개변수 목록에 나타나지만 매개변수 위치를 차지하지 않으며 정기적인 회의가 필요하지 않습니다.
class Student:
name=None
def say_hi(self):
print(f"大家好,我是{self.name},欢迎大家多多关照")
stu=Student()
stu.name="张三"
stu.say_hi()
2. 클래스를 기반으로 객체 생성
class Clock:
id=None
price=None
def ring(self):
import winsound
winsound.Beep(2000, 3000)
clock1=Clock()
clock1.id='1112'
clock1.price=233
print(f"闹钟ID:{clock1.id},价格{clock1.price}")
clock1.ring()
clock2=Clock()
clock2.id='21122'
clock2.price=99.00
print(f"闹钟ID:{clock2.id},价格{clock2.price}")
clock2.ring()
3. 시공방법
Python 클래스는 다음을 사용할 수 있습니다._init_()
생성자 메서드라고 하는 메서드
실현될 수 있습니다:
- 클래스 객체 생성(클래스 생성) 시 자동으로 실행됩니다.
- 클래스 객체 생성(클래스 생성) 시 수신 매개변수는 자동으로
_init_
메소드에 전달되어 사용됩니다.
class Student:
name = None
age=None
tel=None
def __init__(self,name,age,tel):
self.name=name
self.age=age
self.tel=tel
print("student类创建了一个对象")
stu=Student("Cai",20,'13222222222')
print(stu.name)
print(stu.age)
print(stu.tel)
공법상의 주의사항
4. 내장 메소드
__init__
생성자 메소드는Python
클래스의 내장 메소드 중 하나입니다. 이러한 내장 클래스 메소드 각각에는 고유한 특수 기능이 있습니다. 이러한 내장 메소드를 매직 메소드라고 합니다.
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __lt__(self,other):
return self.age<other.age
stu1=Student("张三",20)
stu2=Student("李四",17)
print(stu1<stu2)
print(stu1>stu2)
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __le__(self,other):
return self.age <= other.age
stu1=Student("张三",20)
stu2=Student("李四",20)
print(stu1<=stu2)#True
print(stu1>=stu2)#True
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def __eq__(self,other):
return self.age == other.age
stu1=Student("张三",20)
stu2=Student("李四",20)
print(stu1==stu2)#True
요약하다
5. 포장
객체지향의 세 가지 주요 특징: 상속, 캡슐화, 다형성
캡슐화
개인회원
Private 멤버는 클래스 객체에서 사용할 수 없지만 다른 멤버에서는 사용할 수 있습니다.
상속하다
class 类名(父类名):
内容体
키워드 전달
Pass는 함수 또는 클래스 정의의 무결성을 보장하고 내용이 없거나 비어 있음을 의미하는 일반적인 자리 표시자입니다.
복사
하위 클래스에서 동일한 이름을 가진 속성 또는 메서드 재정의
6. 유형 주석 구문
var_1: int=10
var_2: str="caicai"
var_3: bool=True
class Student:
pass
stu:Student=Student()
my_list:list=[1,2,3]
my_tuple:tuple=(1,2,3)
my_dict:dict={
"caicai":123}
my_list:list[int]=[1,23,3]
my_tuple:tuple[int,str,bool]=(1,"cai",True)
함수 유형 주석
7. 다형성
다형성은 여러 상태를 의미합니다. 즉, 특정 동작을 완료할 때 다른 개체를 사용하면 다른 상태가 발생하는 것입니다.