类与对象

发布时间 2023-12-07 02:58:26作者: 我才是最帅的那个男人

一,类

  个人理解,类是以函数为基础,通过__init__(self),把一些重复使用的参数加以打包于一起,以达到简化工程的目的。(可以最后看这句话)

 1 1 def CarInfo(type,price):
 2  2     print "the car's type %s,price:%d"%(type,price)
 3  3 
 4  4 
 5  5 CarInfo('passat',250000)
 6  6 CarInfo('ford',280000)
 7  7 
 8  8 
 9  9 
10 10 
11 11 class Car:   #定义了一个类
12 12     def __init__(self,type,price):   #在类中编写了一个对象
13 13         self.type = type
14 14         self.price = price
15 15 
16 16     def printCarInfo(self):
17 17         print "the car's Info in class:type %s,price:%d"%(self.type,self.price)
18 18 
19 19 carOne = Car('passat',250000)  #创建了一个对象或者说实例化了一个对象
20 20 carTwo = Car('ford',250000)     
21 21 carOne.printCarInfo()  #通过对象调用其中一个方法
22 22 carTwo.printCarInfo()
23 
24  fnction_class_CompareCode

  运行代码可知,两者结果相同,我想说的是,函数都可以转化为类。下面这个例子是类利用比较好的例子。

 1 class UserInfo:
 2 
 3     def __init__(self):
 4         self.name = None
 5 
 6     def info(self):
 7         print('当前用户名称:%s' %(self.name,))
 8 
 9     def account(self):
10         print('当前用户%s的账单是:....' %(self.name,))
11 
12     def shopping(self):
13         print('%s购买了一个人形抱枕' %(self.name,))
14 
15     def login(self):
16         user = input('请输入用户名:')
17         pwd = input('请输入密码:')
18         if pwd == 'sb':
19             self.name = user
20             while True:
21                 print("""
22                     1. 查看用户信息
23                     2. 查看用户账单
24                     3. 购买抱枕
25                 """)
26                 num = int(input('请输入选择的序号:'))
27                 if num == 1:
28                     self.info()
29                 elif num ==2:
30                     self.account()
31                 elif num == 3:
32                     self.shopping()
33                 else:
34                     print('序号不存在,请重新输入')
35         else:
36             print('登录失败')
37 
38 obj = UserInfo()
39 obj.login()