首页 > 编程语言 > 详细

python-类

时间:2020-04-25 10:32:08      阅读:53      评论:0      收藏:0      [点我收藏+]

类-创建和使用类

 1 class Dog():  #定义Dog类,python中首字母大写的名称指的是类
 2     """A simple attempt to model a dog."""
 3     
 4     def __init__(self, name, age):        #类中的函数称为方法。_init_()是一种特殊方法,每当根据Dog类创建新实例,python会自动运行它。
#开头和末尾的上下划线,是一种约定,旨在避免python默认方法和普通方法发生冲突。
5 """Initialize name and age attributes.""" 6 self.name = name 7 self.age = age 8 9 def sit(self): 10 """Simulate a dog sitting in response to a command.""" 11 print(self.name.title() + " is now sitting.") 12 13 def roll_over(self): 14 """Simulate rolling over in response to a command.""" 15 print(self.name.title() + " rolled over!") 16 17 18 my_dog = Dog(willie, 6) 19 your_dog = Dog(lucy, 3) 20 21 print("My dog‘s name is " + my_dog.name.title() + ".") 22 print("My dog is " + str(my_dog.age) + " years old.") 23 my_dog.sit() 24 25 print("\nMy dog‘s name is " + your_dog.name.title() + ".") 26 print("My dog is " + str(your_dog.age) + " years old.") 27 your_dog.sit()

1)class类包含:

类的属性:类中所涉及的变量 
类的方法:类中函数

2)_init_函数(方法)

1.首先说一下,带有两个下划线开头的函数是声明该属性为私有,不能在类地外部被使用或直接访问。 
2.init函数(方法)支持带参数的类的初始化 ,也可为声明该类的属性 
3.init函数(方法)的第一个参数必须是 self(self为习惯用法,也可以用别的名字),后续参数则可 以自由指定,和定义函数没有任何区别。

 

python-类

原文:https://www.cnblogs.com/BBS2013/p/12764389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!