四周

本周,我学习了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#会报错,类外不能使用私有封装。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 6,031评论 2 16
  • #1 构造方法的练习 # num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 学生编号 ...
    d1a56c4e6b1a阅读 105评论 0 0
  • 编程思想: 面向过程编程(穷人思想)、函数式编程(小资)、面向对象编程(富豪) 面向过程编程 - 算法和逻辑函...
    扎克chen阅读 593评论 0 3
  • 一、面向对象编程编程思想:1.面向过程编程 ---> 算法,逻辑(数学逻辑)2.函数式编程 ---> 函数,模块3...
    Smr_T阅读 571评论 0 0
  • 私有化 .属性和方法访问权限私有的:在类的外部不可以被使用,,也不可以被继承保护的:在类的外部不可以被使用,也可以...
    ChiAo1fei阅读 310评论 0 0

友情链接更多精彩内容