2019-08-08

1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性

class Computer:

    def __init__(self, brand="HP", color="black", ram="10G"):
        self.brand = brand
        self.color = color
        self.ram = ram

    def play_game(self):
        print("we use %s to play computer game" % self.brand)

    def coding(self):
        print("we use %s to code" % self.brand)

    def watch_video(self):
        print("we use %s to watch the video" % self.brand)


computer = Computer("hp", "red", "2g")
# 通过点方法获取类的属性
print(computer.brand, computer.color, computer.ram)  # hp red 2g
# 通过点方法修改类的属性
computer.ram = "4g"
print(computer.ram)  # 4g
# 通过点方法添加类的属性
computer.size = "17"
print(computer.size)  # 17
# 通过点方法删除类的属性
del computer.color
# print(computer.color)  # AttributeError: 'Computer' object has no attribute 'color'
# 通过getattr方法获取属性
print(getattr(computer, "brand"))  # hp
# 通过方法修改类的属性
setattr(computer, "size", 21)
print(getattr(computer, "size"))  # 21
# 通过方法添加类的属性
setattr(computer, "screen", "retina")
print(getattr(computer, "screen"))  # retina
# 通过方法删除类的属性
delattr(computer, "screen")
# print(computer.screen) # AttributeError: 'Computer' object has no attribute 'screen'
# 打游戏
print(computer.play_game())  # we use hp to play computer game
print(computer.coding())  # we use hp to code
print(computer.watch_video())  # we use hp to watch the video

2.声明⼀个人的类和狗的类: 狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄

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

    def bark(self):
        print("%s 会叫”汪汪汪~~~“" % self.name)


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

    def walk_the_dog(self):
        print("%s遛%s" % (self.name, self.pets))
dog=Dog("大黄","yellow",3)
ming=Human("小明",14,dog.name)
print(ming.walk_the_dog())
# 小明遛大黄

import math

3.声明⼀一个圆类,自己确定有哪些属性和方法

class Circle:
    def __init__(self, r):
        self.r = r

    def area(self):
        return math.pi * self.r ** 2

    def perimeter(self):
        return 2 * self.r * math.pi

    def boll(self):
        return math.pi * self.r ** 3


circle = Circle(3)
print(float(circle.perimeter()))
print(circle.area())
print(circle.boll())
# 18.84955592153876
# 28.274333882308138
# 84.82300164692441

你可能感兴趣的:(2019-08-08)