类和对象
self像c++的this指针
class Student:
name = None
age = None
def say_hi(self):#成员方法
print(f"Hi大家好,我是{self.name}")
stu = Student()
stu.name = "张三"
stu.say_hi()
构造方法
- 创建对象的时候自动执行。
def __init__(self,name,age):
self.name = name
self.age = age
魔术方法
python类内置的方法,比如__init__。四个下划线包起来的就叫魔术方法。
getitem
作用就是类如果使用了这个方法。就可以用ants_dataset[0],即对象加索引来找到对应的值(调用__getitem__函数)。
class Mydata(Dataset):
def __init__(self,root_dir,label_dir):
self.root_dir = root_dir
self.label_dir = label_dir
self.path = os.path.join(self.root_dir,self.label_dir)
self.img_path = os.listdir(self.path)
def __getitem__(self, idx):
img_name = self.img_path[idx]
img_item_path = os.path.join(self.root_dir,self.label_dir,img_name)
img = Image.open(img_item_path)
label = self.label_dir
print("这个方法被调用")
return img,label
def __len__(self):
return len(self.img_path)
ants_dataset = Mydata(root_dir = 'hymenoptera_data/train',label_dir = 'ants')
print(ants_dataset[0])
》〉这个方法被调用
(<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x375 at 0x7FBD3FD5E6D8>, 'ants')
call
当调用这个对象的时候,会自动执行__call__.
class Person:
def __call__(self):
print("call")
person = Person()
person()
>>call
私有成员和私有方法
在变量或者方法前加俩下划线__,类似c++的private。
只有类内部的其他成员可以使用。在类的外部无法使用。
class Phone:
__voltage = 1
def __keep(self):
print("keep")
def call(self):
if self.__voltage>=1:
print("calling")
else:
self.__keep()
phone = Phone()
phone.call()
继承
单继承:
class类名(父类名):
继承完之后,父类的成员和方法(除了私有的)都可以用。
多继承:
一个子类继承多个父类。
class类名(父类1,父类2.。。):
先继承的优先级高于后继承的同名方法。
pass关键字
一个类继承了父类,然后这个类如果不想加新东西了,可以用pass。
复写
在子类中重新定义同名的方法和属性。
复写后,调用父类同名成员
class Phone:
producer = 'Apple'
def call_by_5g(self):
print('5g calling')
class Phone20(Phone):
def call_by_5g(self):
print('5g calling by 20')
#方式1
print(f"Phone.producer:{Phone.producer}")
Phone.call_by_5g(self)
# 方式
print(f"Phone.producer:{super().producer}")
super().call_by_5g()
phone = Phone20()
phone.call_by_5g()
类型注解
为什么要类型注解
类型注解语法
在注释中注解
函数的形参注解:
返回值注解
多态
抽象类(接口):
class AC:
def make_hot(self):
pass
class Midea_AC(AC):
def make_hot(self):
print("make hot")
def make_hot(ac:AC):
ac.make_hot()
midea_ac = Midea_AC()
make_hot(midea_ac)