Python: Five Cases to Learn Class Attributes

演習問題
1. 2 つのクラスを設計する:
点クラス。属性は x、y 座標を含む。
矩形クラス(Rectangle)。属性は左上と右下の座標を持つ
メソッド:1. 矩形の面積を計算する 2. 点が矩形内にあるかどうかを判定する
点オブジェクトと矩形オブジェクトをインスタンス化し、矩形の面積を出力し、点が矩形内にあるかどうかを出力する

class Point(object):
# Point クラスの作成時には、x 座標と y 座標を表す int 型の 2 つのパラメーターが必要
def __init__(self, x: int, y: int):
self.x = x
self.y = y


class Rectangle(object):
def __init__(self, top_left: Point, bottom_right: Point):
self. top_left = top_left
self.bottom_right = bottom_right

def get_area(self):
# 面積:長さ * 幅
length = abs(self. bottom_right. x - self. top_left. x)
width = abs(self.top_left.y - self.bottom_right.y)
return length * width

def is_inside(self, point):
# if self.bottom_right.x >= point.x >= self.top_left.x and self.top_left.y >= point.y >= self.bottom_right.y:
# return True
# else:
# return False
return self.bottom_right.x >= point.x >= self.top_left.x and self.top_left.y >= point.y >= self.bottom_right.y

p1 = Point(4, 20) # 左上の点を定義
p2 = Point(30, 8) # 右下の点を定義

r = Rectangle(p1, p2) # 左上と右下の点を矩形に渡す
print(r. get_area()) # 312

# p = Point(10;, 13) # True
p = Point(20;, 30) # False
print(r.is_inside(p))
2. 加算、減算、乗算、除算を実行できる電卓クラスを作成する

class Calculator(object):
@staticmethod
def add(a, b):
return a + b

@staticmethod
def sub(a, b):
return a - b

@staticmethod
def mul(a, b):
return a * b

@staticmethod
def div(a, b):
return a / b

print(Calculator. add(4, 5)) # 9
print(Calculator. sub(4, 5)) # -1
print(Calculator.mul(4, 5)) # 20
print(Calculator. div(4, 5)) # 0.8
3. Person クラスを作成し、Person クラスのオブジェクト数をカウントするクラス属性を追加する

class Person(object):
__count = 0 # クラス属性

def __new__(cls, *args, **kwargs):
x = object.__new__(cls) # メモリを確保し、オブジェクトを作成して、型を Person クラスに設定する
return x

def __init__(self, name, age):
Person.__count += 1
self.name = name
self. age = age

@classmethod
def get_count(cls):
return cls.__count


# オブジェクトが作成されるたびに、__new__ メソッドと __init__ メソッドが呼び出される
# __new__ メソッドを呼び出してメモリを確保する
# __new__ メソッドをオーバーライドしない場合、自動的に object の __new__ メソッドが呼び出される
# object の __new__ メソッドのデフォルト実装は、メモリを確保してオブジェクトを作成すること
p1 = Person('Zhang San', 18)
p2 = Person('Li Si', 19)
p3 = Person('jack', 20)

# print(Person. count) # 3

print(p1, p2, p3)
print(Person. get_count()) # 3

# p4 = object.__new__(Person) # メモリを確保し、オブジェクトを作成して、型を Person に設定する
# p4.__init__('tony', 23)
# print(p4)
4. タイヤ数、車の色、ボディ重量、速度などの属性を持つ Auto クラスを作成し、異なるコンストラクタでインスタンスを作成する。車は加速、減速、停止ができる必要がある。次に、Auto を継承する CarAuto クラスを定義し、エアコンとナビゲーション属性を追加し、メソッドを再実装して加速と減速メソッドをオーバーライドする

class Auto(object):
def __init__(self, color, weight, speed=0, wheel_count=4):
self.wheel_count = wheel_count
self.color = color
self.weight = weight
self.speed = speed

def change_speed(self, x):
"""
速度を変更する
:param x: 変更する車速値。正の数なら加速、負の数なら減速、0 なら停止を意味する
"""
if x == 0:
self.speed = 0 # 渡されたパラメーターが 0 の場合、停止を意味する
return
self.speed += x
if self.speed <= 0 and x < 0
return # return の後にデータを追加することはできない。関数の終了を示す

class CarAuto(Auto):
def __init__(self, color, weight, ac, navigator, speed=0, wheel_count=4):
super(CarAuto, self).__init__(color, weight, speed, wheel_count)
self.navigator = navigator
self.ac = ac

car = CarAuto('White', 1.6, 'Midea', 'Android', 10, 5)

car. change_speed(30)
print(car. speed) # 30

car. change_speed(-40)
print(car.speed) # 0
5. 銀行口座クラス Account があり、名前や残高などの属性を含み、メソッドには入金、出金、残高照査の操作がある。要件:
1. 入金時は入金データのフォーマットに注意すること
2. 出金時は残高が十分かどうかを判定し、残高が不十分な場合は残高不足を通知する必要がある

class Account(object):
def __init__(self, name, balance):
self.name = name
self. balance = balance

def save_money(self, money):
assert isinstance(money, float) or isinstance(money, int), '入金データのフォーマットに注意してください'
self.balance += money

def take_money(self, money):
if self. balance < money:
print('残高不足')
else:
self. balance -= money

def check_balance(self):
return self. balance

a = Account('Zhang San', 8000)
a. save_money(10000)
a. take_money(1000)
print('現在の残高:', a.check_balance())
a. take_money(20000)
print('現在の残高:', a.check_balance())

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone お問い合わせ
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.