1.类就是由一种实例组成的对象,对象 = 属性 + 方法;
2.Python中的类名约定以大写字母开头 , 特征的描述我们称为属性,其实就是一个变量,方法就是python的函数组成;
3.类的创建:
class Country():
def __init__(self,name,city):
self.name = name
self.city = city
def people(self):
retrun (self.name.title() + ' are very friendly!')
def public(self):
return (self.city.title() + ' is very prosperous!')
tt = Country('中国','北京')
print(tt.people())
输出:中国 are very friendly!
print(tt.public())
输出:北京 is very prosperous!
tt = Country('U.S.A','Washington')
输出:U.S.A are very friendly!
print(tt.public())
输出:Washington is very prosperous!
4.类(class)运用:
class Shrimp():
def __init__(self, x):
self.num = x
class Fish():
def __init__(self, x):
self.num = x
class Tank:
def __init__(self, x, y):
self.shrimp = Shrimp(x)
self.fish = Fish(y)
def print_num(self):
return ("水缸里总共有虾 %d 只,小鱼 %d 条!" % (self.turtle.num, self.fish.num))
tt = Pool(3,7)
print(tt.print_num())
输出:水缸里总共有虾 3 只,小鱼 7 条!
Python类与对象:实例化、属性与方法详解
本文介绍了Python中类的定义,如使用大写字母标识,属性(变量)和方法(函数)的概念,以及如何通过`Country`类实例化对象并调用其方法。实例展示了创建类、构造函数和方法的使用,以及类在实际项目中的应用,如`Shrimp`、`Fish`和`Tank`类的组合。
1516

被折叠的 条评论
为什么被折叠?



