python类2

在这里插入图片描述
在这里插入图片描述

class Student:#Student类名,有一个或多个单词组成,每个单词首字母大写,其余小写
    def __init__(self,name,age):
        self.name=name  #self.name为实例属性,进行了一个赋值操作,将局部变量得到name的值赋给了实例属性
        self.__age=age

    #实例方法
    def eat(self):
        print(self.name+'吃饭了######')

stu1 = Student('张三',20)
print(dir(stu1))#在类的外部可以通过dir()查看访问方式,如_Student__age
print(stu1._Student__age)

在这里插入图片描述
在这里插入图片描述

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def info(self):
        print(self.name,self.age)

class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no = stu_no

class Teacher(Person):
    def __init__(self,name,age,ttt):
        super().__init__(name,age)
        self.ttt = ttt

stu = Student('在上述',20,'111')
t = Teacher('离散',30,10)

stu.info()
t.info()


"""
多继承
"""

class A(object):
    pass

class B(object):
    pass

class C(A,B):
    pass

在这里插入图片描述

class Person(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def info(self):
        print(self.name,self.age)

class Student(Person):
    def __init__(self,name,age,stu_no):
        super().__init__(name,age)
        self.stu_no = stu_no

    def info(self):
        super().info()#重写
        print(self.stu_no)

在这里插入图片描述

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __str__(self):
        return '{0}今年{1}岁了'.format(self.name,self.age)

stu = Person('阿斯蒂芬',20)
print(stu)#默认调用__str__()方法,重写这个方法返回对象的描述
print(type(stu))

在这里插入图片描述
具有相同方法或属性!!!!
在这里插入图片描述

class Animal(object):
    def eat(self):
        print('动物会吃')

class Dog(Animal):
    def eat(self):
        print('狗吃肉')

class Cat(Animal):
    def eat(self):
        print('猫吃鱼')

class Person(object):
    def eat(self):
        print('人吃动物')


#定义一个函数
def fun(obj):
    obj.eat()

#开始调用函数

fun(Cat())
fun(Dog())
fun(Animal())
print('-------------------------------------')
fun(Person())

在这里插入图片描述
在这里插入图片描述
__new__在前创建对象
__init__在后为对象实例属性赋值

class Person(object):
    def __new__(cls, *args, **kwargs):
        print('__new__被调用执行,cls的id值为{0}'.format(id(cls)))
        obj = super().__new__(cls)
        print('创建的对象的id为{0}'.format(id(obj)))
        return obj

    def __init__(self, name, age):
        print('__init__被调用执行,self的id值为{0}'.format(id(self)))
        self.name = name
        self.age = age


print('object类对象的id值为{0}'.format(id(object)))
print('Person类对象的id值为{0}'.format(id(Person)))

p = Person('阿松大',20)
print('p的Person类的id值为{0}'.format(id(p)))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43350706

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值