PYTHON教程之类

51changxuePython评论230 views阅读模式

PYTHON教程之类

PYTHON教程之类

#1.创建类
#class 定义一个类, 后面的类别首字母推荐以大写的形式定义,比如Calculator. class可以先定义自己的属性,
# 比如该属性的名称可以写为 name='Good Calculator'. class后面还可以跟def, 定义一个函数.
#  比如def add(self,x,y): 加法, 输出print(x+y). 其他的函数定义方法一样,注意这里的self 是默认值.
class Dog():
    """A simple attempt to model a dog."""
    #类的初始化__init__可以理解成初始化class的变量,取自英文中initial
    #最初的意思.可以在运行时,给初始值附值
    def __init__(self, name, age):
        """Initialize name and age attributes."""
        self.name = name#类的属性
        self.age = age

    def sit(self):#类的方法
        """Simulate a dog sitting in response to a command."""
        print(self.name.title() + " is now sitting.")

    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(self.name.title() + " rolled over!")

#类的调用或者叫创建实例,调用类时要加()
my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)
#类的属性调用,my_dog.name
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
#类的方法调用方法
my_dog.sit()

print("\nMy dog's name is " + your_dog.name.title() + ".")
print("My dog is " + str(your_dog.age) + " years old.")
your_dog.sit()

运行结果:

"D:\Program Files\python\python.exe" "D:/Program Files/python/example/PYTHON教程之类.py"
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.

My dog's name is Lucy.
My dog is 3 years old.
Lucy is now sitting.

Process finished with exit code 0

 

继续阅读
51changxue
  • 本文由 发表于 2018年4月6日 11:26:27
  • 转载请务必保留本文链接:https://51changxue.com/408.html
pycharm永久破解激活教程 Python

pycharm永久破解激活教程

PyCharm是一种Python IDE,带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、Project管理、代码跳转、智能提示、自动完成、...
Tkinter控件快速引用总结 Python

Tkinter控件快速引用总结

  文件名称: Tkinter控件快速引用总结代码.rar 文件大小: 4k 更新日期: 2018-7-29 文件版本: V1.0 免责声明: 本站大部分下载资源收集于网络,只做学习和交流使...
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定