假如我有一直小猫‘花花’,今天1岁了,是一只会转圈圈和玩线团的小可爱,通过类来实现,因为这样当别人也有类似的小猫时就可直接使用了
#定义一个猫类
class Cat():
def __init__(self,name,age):
self.name=name
self.age=age
#玩线团
def play_clew(self):
print(self.name.title()+" is now playing with a ball of string")
#转圈圈
def turn_around(self):
print(self.name.title()+' is turning around!')
#实例化我的小猫
mycat=Cat('huahua',1)
print('My cat\'s name is '+mycat.name.title())
print('My cat\'s age is '+str(mycat.age) +' years old')
输出:
My cat’s name is Huahua
My cat’s age is 1 years old
注意:
1、定义Cat类时,首字母要大写,代表类
2、init()方法相当于是一个内部转化方法,将我们提供的参数转化为类内部可以使用的参数,如name经过转化后就可以在类内部调用了
3、实例化时,要使用类名添加参数的方式,并将实例化的值赋给一个变量进行存储
4、接着就可以使用实例化后的变量访问属性和方法了,访问方法示例如下
#将上边的代码复制过来,这里省略不写了
(省略......)
mycat.play_clew()
mycat.turn_around()
输出:
Huahua is now playing with a ball of string
Huahua is turning around!
提示,开头说了我有一只小猫,别人也可能有一只类似的小猫,当要创建别人的小猫时再实例化一个就可以了
练习
建立一个人员类,有姓、有名、还有存储不同数量的问候语,
class User():
def __init__(self,first_name,last_name,*info):
self.first_name=first_name
self.last_name=last_name
self.info=info
def describe_user(self):
print('The user\'s name is '+self.first_name.title()+' '+self.last_name.title())
def greet_user(self):
for inf in self.info:
print(self.first_name.title()+' '+self.last_name.title() +' '+inf)
han=User('han','meimei','nihao','Hello')
han.describe_user()
han.greet_user()
输出:
The user’s name is Han Meimei
Han Meimei nihao
Han Meimei Hello