python教程27-魔法方法介绍、内置属性、把对象当作字典操作、类属性和对象属性、私有属性和方法的使用

本教程涵盖了Python编程中的关键概念,包括魔法方法的介绍,如何利用内置属性,将对象作为字典进行操作,理解类属性和对象属性的区别,以及如何有效地使用私有属性和方法。适合Python初学者入门学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python教程_小白入门2021/3/16

学习目标
在这里插入图片描述

P159 魔法方法介绍

在这里插入图片描述

# class Person(object):
#     def __init__(self, name, age):
#         self.name = name
#         self.age = age
#
#     def eat(self):
#         print(self.name + "正在吃东西")
#
#
# p1 = Person('张三', 18)
# p2 = Person('lisi', 20)
#
# p1.eat()        # 张三正在吃东西
# -------------------------------------------------------------------------------
# 算术运算符相关的方法
class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        # if self.name == other.name and self.age == other.age:
        #     return True
        # elif:
        #     return False
        return self.name == other.name and self.age == other.age

    def __ne__(self, other):  # 使用! = 运算符自动调用这个方法
        print('2333')
        return True

    def __gt__(self, other):  # great than 使用 > 会自动调用这个方法
        return self.age > other.age

    def __ge__(self, other):  # 使用 >=会自动调用这个方法
        return self.age >= other.age

    def __lt__(self, other):  # less than 使用 < 会自动调用这个方法
        return self.age < other.age

    def __le__(self, other):  # 使用 <=会自动调用这个方法
        return self.age <= other.age

    def __add__(self, other):  # 使用 + 会自动调用这个方法
        return self.age + other.age

    def __sub__(self, other):  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值