定义手机类,手机有品牌,价格和颜色三个属性,有打电call和sendMessage两个功能
时间: 2024-01-14 17:04:58 浏览: 101
下面是一个简单的Python示例代码,定义了一个手机类,它具有品牌、价格和颜色三个属性,以及打电话和发送短信两个方法:
```python
class Phone:
def __init__(self, brand, price, color):
self.brand = brand
self.price = price
self.color = color
def call(self, number):
print("Calling {}...".format(number))
def send_message(self, number, message):
print("Sending message to {}: {}".format(number, message))
```
使用示例:
```python
# 创建一个手机对象
my_phone = Phone("Apple", 999, "Black")
# 访问属性
print("My phone is a {} phone, which costs {} dollars and has a {} color.".format(my_phone.brand, my_phone.price, my_phone.color))
# 调用方法
my_phone.call("123456789")
my_phone.send_message("123456789", "Hello!")
```
输出:
```
My phone is a Apple phone, which costs 999 dollars and has a Black color.
Calling 123456789...
Sending message to 123456789: Hello!
```
阅读全文