PYTHON教程之类

2018年4月6日11:26:27 发表评论 164 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

发表评论

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