python中类的学习笔记(源码版)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python中类的学习笔记(源码版),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2168字,纯文字阅读大概需要4分钟。
内容图文
![python中类的学习笔记(源码版)](/upload/InfoBanner/zyjiaocheng/1261/011834c2987141d082dd5b489dbb1099.jpg)
#定义一个类(define a class )
class Cat:
#属性(attribution)
#方法(methods)
def eat(self):
print("cat is eating a fish.")
def drink(slef):
print("cat is drinking milk.")
def introduce(self):
print("%s‘s age is %d"%(tom.chinese_name,tom.age))
#创建一个对象(creating an object)
tom = Cat()
#调用一个对象的方法(method to invoke an object)
tom.eat()
tom.drink()
#蠢办法添加属性(stupid method to add attributions)
tom.chinese_name = "汤姆"
tom.age = 18
#获取对象的属性(the first way to get properties of objects )
tom.introduce()
#创建多个对象,这里创建第二个对象blue_cat(create multiple objects,and the second creates bule cat)
blue_cat = Cat()
blue_cat.chinese_name = "蓝猫"
blue_cat.age = 8
blue_cat.introduce()
1.2执行第一段代码的输出
[root@localhost class]# python test.py
cat is eating a fish.
cat is drinking milk.
汤姆‘s age is 18
汤姆‘s age is 18
‘‘‘
那这里我们可以看到两个不同的对象调用方法后输出了相同的结果,这就出现问题了,
那怎么解决上面的问题,且看下面的代码。
‘‘‘
2.1第2种方式
self的加入,解决了上面的问题。
#定义一个类(define a class )
class Cat:
#属性(attribution)
#方法(methods)
def eat(self):
print("cat is eating a fish.")
def drink(slef):
print("cat is drinking milk.")
def introduce(self):
print("%s‘s age is %d."%(self.chinese_name,self.age))
#创建一个对象(creating an object)
tom = Cat()
#调用一个对象的方法(method to invoke an object)
tom.eat()
tom.drink()
#蠢办法添加属性(stupid method to add attributions)
tom.chinese_name = "汤姆"
tom.age = 18
#获取对象的属性(the first way to get properties of objects )
tom.introduce()
#创建多个对象,这里创建第二个对象blue_cat(create multiple objects,and the second creates bule cat)
blue_cat = Cat()
blue_cat.chinese_name = "蓝猫"
blue_cat.age = 8
blue_cat.introduce()
2.2第二段代码的输出
[root@localhost class]# python test.py
cat is eating a fish.
cat is drinking milk.
汤姆‘s age is 18.
蓝猫‘s age is 8.
3 init和str的使用
class Cat:
"""定义了一个Cat类"""
#初始化对象
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return "%s的年龄是:%d"%(self.name,self.age)
#方法
def eat(self):
print("猫在吃鱼....")
def drink(self):
print("猫正在喝牛奶.....")
def introduce(self):
print("%s的年龄是:%d"%(self.name, self.age))
#创建一个对象
tom = Cat("汤姆", 40)
bule_cat = Cat("蓝猫", 10)
print(tom)
print(bule_cat)
[root@localhost class]# python test2.py
汤姆的年龄是:40
蓝猫的年龄是:10
原文:http://blog.51cto.com/huwho/2103478
内容总结
以上是互联网集市为您收集整理的python中类的学习笔记(源码版)全部内容,希望文章能够帮你解决python中类的学习笔记(源码版)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。