美文网首页python
创建和使用类

创建和使用类

作者: 庵下桃花仙 | 来源:发表于2018-11-13 22:26 被阅读2次
class Dog(): # 类的约定,首字母大写
    """一次模拟小狗的简单尝试"""

    def __init__(self, name, age): # 创建新实例时,自动运行
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self):
        """模拟小狗被命令时蹲下"""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """模拟小狗被命令时打滚"""
        print(self.name.title() + " roll over!")

my_dog = Dog('willie', 6)

print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie roll over!
# 9 - 1
class Restaurant():

    def __init__(self, name, type):
        self.name = name
        self.type = type

    def describe_restaurant(self):
        print("The name of the restaurant is: " + self.name.title() + ".")
        print("The type of restaurant is: " + self.type + ".")

    def open_restaurant(self):
        print("The restaurant is open!")

restaurant = Restaurant('打牙祭', 'fast food')
restaurant.describe_restaurant()
restaurant.open_restaurant()

# 9 - 2
class User():

    def __init__(self, first_name, last_name, telephone):
        self.first_name = first_name
        self.last_name = last_name
        self.telephone = telephone

    def describe_user(self):
        print("First name is: " + self.first_name.title())
        print("Last name is: " + self.last_name.title())
        print("Telephone is: " + str(self.telephone))

    def greet_user(self):
        print("Hello, " + self.first_name.title() + self.last_name.title() + "!")

user = User('tao', 'huaxian', 999999999)
user.describe_user()
user.greet_user()
The name of the restaurant is: 打牙祭.
The type of restaurant is: fast food.
The restaurant is open!
First name is: Tao
Last name is: Huaxian
Telephone is: 999999999
Hello, TaoHuaxian!

相关文章

  • 第32课:类

    预习: class、__init__、 9.1 创建和使用类 9.1.1创建Dog类 2,在Python2.7中创...

  • python(17):类(1)

    1.创建和使用类 2.使用类和实例

  • 创建和使用类

  • 共读Python编程-类卡

    创建和使用类 创建类 使用class关键字定义类 类名后使用冒号结束 方法init()init方法是类的构造函数,...

  • ExtJS的学习和使用-2

    1类的声明和调用 2创建和使用

  • python 字典

    1. 字典的背景 2. 创建和使用字典 2. 创建和使用字典 2.2.1 使用dict类来创建 2.2.2 字典的...

  • 线程

    如何创建和使用线程 继承 Thread 类。 实现 Runnable 接口。 使用 Callable 和 Futu...

  • 类的创建和使用

    类的创建 lazy property:调用的时候才初始化 Type property:static 关键字 比较两...

  • python基础(六)

    类 1、创建和使用类 1.1 创建Do类 ``` class Dog(): #类的首字母大写 '''一次模拟小狗...

  • 06类

    [TOC]根据类来创建对象被称为实例化,能让你使用类的实例. 创建和使用类 1.方法init() 类中的函数称为方...

网友评论

    本文标题:创建和使用类

    本文链接:https://www.haomeiwen.com/subject/arerfqtx.html