本周,我学习了python中的类对象,创建类的语句最基本的是:
class Person:
name = None
gender = None
age = None
nationality = None
在后面可以添加函数如:
def say_hi(self):#函数括号内必须加self,之后再加参数
print(f"大家好,我是{self.name}")
def say_hi2(self,a):
print(f"大家好,我是{self.name},{a}")
之后应用这个类:
person_1 = Person()
person_1.name = "渣渣灰"
person_1.gender = "男"
person_1.age = 18
person_1.nationality = "中国"
print(person_1.nationality)
person_1.say_hi()
person_1.say_hi2("一起来玩贪玩蓝月")
如果在类中使用__init__方法,应用会变简单
class Person:
def __init__(self,name,gender,age,nationality):#自动方法,会自动将类中的变量输入函数中
self.name = name
self.gender = gender
self.nationality = nationality
self.age = age
应用方法如下:
per = Person("渣渣灰","男",'18',"中国")
print(per)
除此之外,类对象中还有许多其他魔术方法:
class Person:
def __init__(self, age):
self.age = age
def __lt__(self, other):#用于比较小于,反过来也能比较大于
return self.age < other.age
def __eq__(self, other):#判断是否等于
return self.age == other.age
def __le__(self, other):#判断小于等于
return self.age <= other.age
返回值都是布尔常数,分别是False,True
应用如下:
stu1 = Person(11)
stu2 = Person(18)
stu3 = Person(18)
print(stu1 > stu2)#结果为False
print(stu3 == stu2)#结果为True
print(stu1 <= stu2)#结果为False
print(stu1 < stu2)#结果为True
除方法外,还有其他用法,如私有封装:
class Phone:
__current_voltage =2#私有变量,在类外不能使用,在类内可以使用
__is_5G_enable =True
def __keep_single_core(self):
print("单核运行")
def __check_5G(self):
if self.__is_5G_enable:
print("5G通话")
else:
print("改为4G通话")
def call_by_5G(self):
if self.__current_voltage >=1:#在类内使用私有封装
print("5G开始")
else:
self.__keep_single_core()
print("5G无法打开")
def call_by_5G2(self):
self.__check_5G()
print("正在通话中")
应用:
ph = Phone()
ph.call_by_5G()
ph.call_by_5G2()
ph.__current_voltage =3#会报错,类外不能使用私有封装。