類和對象
例子1
class Student:
name = None
gender = None
nationality = None
native_place = None # 籍貫
age = None
# 類內(nèi)的成員方法,第一個(gè)參數(shù)必須為 self,
# self相當(dāng)于是當(dāng)前對象
def say_hi(self):
print(f"大家好,我是{self.name}")
def say_hi2(self, msg):
print(f"大家好,我是{self.name}, {msg}")
# 2.創(chuàng)建對象
stu1 = Student()
# 3. 對象屬性
stu1.name = "王偉"
stu1.gender = "男"
stu1.nationality = "中國"
stu1.native_place = "福建省"
stu1.age = 30
# 4.輸出對象信息
print(stu1.name)
print(stu1.gender)
print(stu1.nationality)
print(stu1.native_place)
print(stu1.age)
stu1.say_hi()
stu1.say_hi2("多多關(guān)照")
輸出結(jié)果:
王偉
男
中國
福建省
30
大家好,我是王偉
大家好,我是王偉, 多多關(guān)照
例子2:構(gòu)造方法__init__()
與C++的構(gòu)造函數(shù)類似:
class Student:
# 這里聲明其實(shí)不寫也可以,構(gòu)造方法里會(huì)自動(dòng)聲明+定義
name = None
age = None
tel = None
# !!
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
print("Student類創(chuàng)建了一個(gè)類對象")
stu1 = Student("陳奕迅", 39, 1292392992)
print(stu1.name)
print(stu1.age)
print(stu1.tel)
魔術(shù)方法
魔術(shù)方法類似于C++中的運(yùn)算符重載
例子1:str 和 lt
這個(gè)方法的作用就是控制類轉(zhuǎn)換為字符串時(shí)的行為
class Student:
# !!
def __init__(self, name, age, tel):
self.name = name
self.age = age
self.tel = tel
print("Student類創(chuàng)建了一個(gè)類對象")
def __str__(self):
return f"Student對象的成員name:{self.name}, age:{self.age}, tel:{self.tel}"
# 相當(dāng)于重載 < 運(yùn)算符,使得對象可以用 < 和 >
def __lt__(self,other):
return self.age < other.age
# 使得對象間 >= 和 <= 可用
def __le__(self, other):
return self.age <= other.age
# ==運(yùn)算符重載
def __eq__(self, other):
return self.age == other.age
stu1 = Student("陳奕迅", 39, 1292392992)
stu2 = Student("周杰倫", 39, 1239200233)
print(stu1 < stu2) # False
print(stu1 > stu2) # False
print(stu1 <= stu2) # True
print(stu1 >= stu2) # True
print(stu1 == stu2) # 如果類內(nèi)沒有實(shí)現(xiàn) __eq__,則比較的時(shí)內(nèi)存地址,False
print(stu1)
輸出結(jié)果:
Student類創(chuàng)建了一個(gè)類對象
Student類創(chuàng)建了一個(gè)類對象
False
False
True
True
True
Student對象的成員name:陳奕迅, age:39, tel:1292392992
封裝
例子1: 私有成員變量和方法
以兩個(gè)下劃線__
開頭的變量或方法,就是私有的成員
class Phone:
# 成員名前有 __ 就是私有成員
__current_voltage = 0.5 # 手機(jī)當(dāng)前電壓
def __keep_single_core(self):
print("CPU以單核模式運(yùn)行")
def call_by_5g(self):
# 只有類內(nèi)
if self.__current_voltage >= 1:
print("5g通話已開啟")
else:
self.__keep_single_core()
print("電量不足,無法使用5g通話,并設(shè)置為單核模式")
phone = Phone()
phone.call_by_5g();
# 類外無法使用私有成員,如下:
# print(phone.__current_voltage)
# phone.__keep_single_core()
輸出結(jié)果:
CPU以單核模式運(yùn)行
電量不足,無法使用5g通話,并設(shè)置為單核模式
繼承
簡單的說就是復(fù)用其他類的內(nèi)容
語法: class 類名(父類名):
例子1
class Phone:
IMEI = None
producer ="Apple"
def call_by_4g(self):
print("4g通話")
# Phone2023 繼承 Phone,或稱作 Phone2023 派生自 Phone
class Phone2023(Phone):
face_id = "10001"
def call_by_5g(self):
print("5g通話")
phone = Phone2023()
print(phone.producer)
phone.call_by_4g()
phone.call_by_5g()
輸出結(jié)果:
Apple
4g通話
5g通話
例子2:多繼承
class Phone:
IMEI = None
producer ="Apple"
def call_by_4g(self):
print("4g通話")
class NFCReader:
nfc_type = "第五代"
producer = "Samsung"
def read_card(self):
print("NFC讀卡")
def write_card(self):
print("NFC寫卡")
class RemoteControl:
rc_type = "紅外遙控"
def control(self):
print("紅外遙控開啟")
class MyPhone(Phone, NFCReader, RemoteControl):
pass # 啥也不想寫就填 pass
phone = MyPhone()
phone.call_by_4g()
phone.read_card()
phone.write_card()
phone.control()
# 注意Phone, NFCReader都有 producer 成員
# 注意這里 producer 使用的是Phone::producer,即繼承中左邊的類的成員
print(phone.producer)
輸出結(jié)果:
4g通話
NFC讀卡
NFC寫卡
紅外遙控開啟
Apple
例子3:子類復(fù)寫父類成員;子類使用父類的成員
class Phone:
IMEI = None
producer ="Apple"
def call_by_5g(self):
print("5g通話")
class MyPhone(Phone):
# 復(fù)寫父類的成員
producer = "Nokia"
def call_by_5g(self):
print("開啟CPU單核模式,確保通話時(shí)省電")
# 使用父類成員方式1
# print(f"父類的廠商是{Phone.producer}")
# Phone.call_by_5g(self) # 注意這種方法要傳 self
# 使用父類成員方式2 super()
print(f"父類的廠商是{super().producer}")
super().call_by_5g()
print("關(guān)閉CPU單核模式,確保性能")
phone = MyPhone()
phone.call_by_5g()
print(phone.producer)
輸出結(jié)果:
開啟CPU單核模式,確保通話時(shí)省電
父類的廠商是Apple
5g通話
關(guān)閉CPU單核模式,確保性能
Nokia
類型的注解
給類型加上注解之后,比如給函數(shù)參數(shù)加注解,則調(diào)用函數(shù)時(shí),智能提示就能提示輸入?yún)?shù)類型。
一般是無法看出來的參數(shù)類型才建議加注解
例子1
tu:Student = Student()
# 基礎(chǔ)容器類型注解
my_list: list = [1, 2, 3]
my_tuple: tuple = (1, 2, 3)
my_dict: dict = {"lisi": 44}
# 容器類型詳細(xì)注釋
my_list1: list[int] = [1, 2, 3]
my_tuple1: tuple[int, str, bool] = (1, "apple", False)
my_dict1: dict[str, int] = {"lisi": 44}
# 在注釋中進(jìn)行類型注解
var_4 = random.randint(1, 10) # type: int
var_5 = json.loads('{"name": "wangwu"}') # type:dict[str, str]
def func():
return 10
var_6 = func() # type: int
# 類型注解的限制
# 如果注解和實(shí)際類型不符合,pycharm提示按用戶注解來
var_7: int = "nokia"
var_8: str = 222
例子2:函數(shù)參數(shù)類型進(jìn)行注解
# 對形參類型進(jìn)行注解
def add(x: int, y: int):
return x + y
# 對返回值進(jìn)行類型注解
def func(data: list) ->list:
return data
# 類型注解只是起提示作用,下面語句仍能正常運(yùn)行
print(type(func(1))) # <class 'int'>
注解:
添加注解后,調(diào)用函數(shù)按下 ctrl + p會(huì)有如下提示
例子3:union聯(lián)合類型注解
from typing import Union
# 表示列表元素類型可為 int 或 str
my_list: list[Union[int, str]] = [1, 2, 3]
# 表示函數(shù)參數(shù)類型可為 int 或str
def func(data: Union[int, str]) -> Union[int, str]:
pass
多態(tài)
例子1
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("汪汪汪")
class Cat(Animal):
def speak(self):
print("喵喵喵")
# 根據(jù)不同參數(shù)來調(diào)用對應(yīng)的對象,基類接受派生類
def make_noise(animal: Animal):
animal.speak()
dog = Dog()
cat = Cat()
make_noise(dog)
make_noise(cat)
輸出結(jié)果:
汪汪汪
喵喵喵
例子2
# 空調(diào)抽象基類
class AC:
def cool_wind(self):
pass
def hot_wind(self):
pass
def swing_l_r(self):
pass
class Midea_AC(AC):
def cool_wind(self):
print("美的空調(diào)制冷")
def hot_wind(self):
print("美的空調(diào)制熱")
def swing_l_r(self):
print("美的空調(diào)左右擺風(fēng)")
class GREE_AC(AC):
def cool_wind(self):
print("格力空調(diào)制冷")
def hot_wind(self):
print("格力空調(diào)制熱")
def swing_l_r(self):
print("格力空調(diào)左右擺風(fēng)")
def make_cool(ac: AC):
ac.cool_wind()
midea_ac = Midea_AC()
gree_ac = GREE_AC()
make_cool(midea_ac)
make_cool(gree_ac)
輸出:
美的空調(diào)制冷文章來源:http://www.zghlxwxcb.cn/news/detail-489792.html
格力空調(diào)制冷文章來源地址http://www.zghlxwxcb.cn/news/detail-489792.html
到了這里,關(guān)于python基本語法知識(shí)(五)——面向?qū)ο蟮奈恼戮徒榻B完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!