pyhton 基础入门 -------面向对象 、类方法 、对象方法

面向对象的特点:封装  继承  多态

class 子类(父类)

继承的特点          class张无忌(张翠山)

  • 子类拥有父亲的属性和方法   张无忌  拥有 张翠山的 财产 房产  衣服
  • 子类拥有自己的属性和方法   张无忌拥有  教主  老婆
  • 子类可以重写 (覆盖、改写)父类的方法    张无忌改进武当剑派

人类 ——男人类  女人类 

class People(object):
    def __init__(self, name="", age="", sex=""):
        self.name = name
        self.age = age
        self.sex = sex

    def eat(self):
        print("人类需要细嚼慢咽吃饭")


class Man(People):
    def __init__(self, name="", age="", sex="", hu_zi="",):
        # super:当前类的父类的对象
        # self:当前类的对象
        super(Man, self).__init__(name, age, sex)
        self.hu_zi = hu_zi

    def smoke(self):
        print("{}抽烟".format(self.name))

    def eat(self):
        super(Man, self).eat()
        print("{}吃了3碗饭".format(self.name))


m = Man(name="张三", age="20", sex="男", hu_zi="络腮胡")
m.eat()
m.smoke()

什么时候用super?

如果想保留父亲的功能但是又想拓展自己的功能

类方法  和  静态方法

# self:当前类的对象
# super:当前类的父类的对象
# cls:当前类
# 类方法 和 静态方法
class People(object):
    count = 0
    color = ""

    def __init__(self, name="", age=0):
        self.name = name
        self.age = age

    def eat(self):
        print("{}正在吃饭".format(self.name))

    @classmethod # 类方法  调用形式   类名.方法名()
    def log_info(cls):
        # cls=class 表示当前类
        print("这是类方法-{}".format(cls.count))

    @staticmethod # 静态方法, 不需要用self/cls (类和对象都可以打点调用静态方法)
    def method():
        print("hello world")


People.log_info()
# People.eat()  类名不能调用对象方法/对象属性
People.method()

p = People()
p.meth

练习
1. 在现有代码基础上创建一个男学生类,具备 班级,学号等属性
2. 学生 具备 学习方法
3. 学生需要先吃早饭再细嚼慢咽
4. 学生调用学习方法,输出 ***在学习
"""
class ManStudent(Man):
    def __init__(self, name="", age="", sex="", hu_zi="", stu_class="", stu_id=""):
        super(ManStudent, self).__init__(name, age, sex, hu_zi)
        self.stu_class = stu_class
        self.stu_id = stu_id

    def study(self):
        print("{}在学习".format(self.name))

    def eat(self):
        print("学生先吃早饭")
        super(Man, self).eat()


s = ManStudent(name="李四")
s.eat()
s.study()




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值