Python入门day06(类)

创建类

"""
#类名一般首字母大写
class Name():
    def __init__(self,one,two):
        #初始化属性
        self.one = one
        self.two = two
        self.three = 0 #未传值,定义时必须初始化

    def 方法一(self):
        函数体
    def 方法二(self):
        函数体
"""
#创建一个小狗类
class Dog():
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.sex = 'gong'

    def information(self):
        """输出小狗信息"""
        print("My dog's name is " + self.name.title() + ", it's age is " + str(self.age) + ", it's sex is " + self.sex)

    def sit(self):
        """模拟小狗坐下"""
        print(self.name.title() + ' is now sitting')

    def roll_over(self):
        """模拟小狗打滚"""
        print(self.name.title() + ' rolled over')

    def update_age(self,age):
        self.age = age

类的使用

#创建一个小狗实例
my_dog = Dog('jim',8)#必须初始化_init_()方法
#调用值
print("My dog's name is " + my_dog.name.title())
#调用方法
my_dog.information()
my_dog.sit()
my_dog.roll_over()

修改类中属性值

#修改类中属性值

#1.直接修改
my_dog = Dog('jim',5)
print(my_dog.name.title() + " is " + str(my_dog.age))
#Jim is 5
my_dog.age += 1
print(my_dog.name.title() + " is " + str(my_dog.age))
#Jim is 6

#2.通过方法修改属性的值
my_dog.update_age(8)
print(my_dog.name.title() + " is " + str(my_dog.age))
#Jim is 8

创建子类

class Dog_son(Dog):
    def __init__(self,name,age,color):
        super().__init__(name,age)
        self.color = color#加一个color属性
    #加一个方法
    def color_print(self):
        print("My dog's color is " + self.color)

子类调用方法

dog_son = Dog_son('jim',4,'yellow')

#调用继承的父类方法
dog_son.information()

#调用子类新写的方法
dog_son.color_print()

# My dog's name is Jim, it's age is 4, it's sex is gong
# My dog's color is yellow

子类重写父类方法

#子类重写父类方法
class Dog_son(Dog):
    def __init__(self,name,age,color):
        super().__init__(name,age)
        self.color = color

    def color_print(self):
        print("My dog's color is " + self.color)

    def information(self):
        print("change the 父类方法")

dog_son = Dog_son('jim',4,'yellow')
#掉用修改后的方法
dog_son.information()
#change the 父类方法

将实例用作属性

#创建一个类,作为属性
class Area():
    def __init__(self,area):
        self.area = area

    def area_print(self):
        print("this dog is from " + self.area)

#创建一个Dog子类
class Dog_son(Dog):
    def __init__(self,name,age):
        super().__init__(name,age)
        self.areatry = Area('hunan')#将Area实例作为属性

#调用area_print()方法
dog_son = Dog_son('jim',4)
dog_son.areatry.area_print()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值