python类与对象

本文详细介绍了如何在Python中实现类的继承,包括People和Student类的定义、构造方法、私有属性和方法的使用。重点展示了多继承的特点,以及如何调用父类的方法。通过实例演示了如何创建和操作子类,以及在实际开发中的应用场景。

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

# 定义一个类
class People:
    # 定义基本属性
    name = 'default'
    age = 0
    # 定义私有属性
    __sex = 'default'

    # 定义构造方法,self代表类的实例,而非类,类的方法中第一个参数都要是self
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.__sex = sex

    # 定义私有方法
    def __is_man(self):
        if self.__sex == 'man':
            return 'he'
        else:
            return 'she'

    def describe(self):
        print('{} is {} years old and {} is a {}!'.format(self.name, self.age, self.__is_man(), self.__sex))
# 定义一个子类继承People类
class Student(People):
    grade = 0
    __sex = 'default'

    # 构造函数
    def __init__(self, name, age, sex, grade):
        # 调用父类的构造函数
        People.__init__(self, name, age, sex)
        self.grade = grade
        self.__sex =sex

    def __is_man(self):
        if self.__sex == 'man':
            return 'he'
        else:
            return 'she'

    # 重写父类方法
    def describe(self):
        print('{} is {} years old and {} got {}!'.format(self.name, self.age, self.__is_man(), self.grade))
# 实例化
p = People('Berry', 18, 'man')
# 调用实例变量
print(p.name)  # Berry
# 调用方法
p.describe()
# Berry is 18 years old and he is a man!
# 实例化父类
p = People('Berry', 18, 'man')
# 调用实例变量
print(p.name)  # Berry
# 调用方法
p.describe()
# Berry is 18 years old and he is a man!
# 实例化子类
stu = Student('Sim', 12, 'man', 100)
stu.describe()
# Sim is 12 years old and he got 100!

Python同样有限的支持多继承形式。需要注意圆括号中父类的顺序,若是父类中有相同的方法名,而在子类使用时未指定,python从左至右搜索 即方法在子类中未找到时,从左到右查找父类中是否包含方法。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值