python之7-1类

时间:2022-05-10 06:49:43
  • 面向对象的编程,其实是将对象抽象成类,然后在类中,通过init定义实例初始化函数和多个操作实例的函数.

  • 整个类就如同一个模板,我们可以用这个模板生成众多具现实例,并赋予实例动作.

  • py中定义类的大致格式如下:

class 类名():
类变量名 =
类名.类变量名 #调用类变量
def _init_(self,参数1,参数2): #这里的参数也可以没有,即可以直接 self.属性 = 值 而self每次对应的就是实例自己
self.属性1 = 参数1
self.属性2 = 参数2
def 实例方法函数名(self,方法变量1,方法变量2):
函数体 实例名 = 类名(参数1,参数2) #实例创建
实例名.实例方法函数名() #实例动作函数调用
  • 注释1:self这里就是实例统称,属性1和属性2是类的属性,然后将属性1和属性2获得的参数传递给实例,构建实例的属性,最后这些实例属性,被方法函数所调用

  • 注释2:

类 就像是 包;

init函数 就如同包里面的 init模块 ,来介绍这个类;

方法函数 就像是包里面的 其他模块,来具体实现类的操作

  • 例子1:
#!/usr/bin/python
# Filename: objvar.py class Person:
'''Represents a person.'''
population = 0 def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name # When this person is created, he/she
# adds to the population
Person.population += 1 def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population def sayHi(self):
'''Greeting by the person. Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany() kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany() swaroop.sayHi()
swaroop.howMany()
  • 例子2:获取一组连续数字的中间数字
#!/usr/bin/python2.6
class lis:
def __init__(self, start, end):
self.start = start
self.end = end
def test(self):
if ( self.start % 2 == 0 and self.end % 2 == 0 ) or ( self.start % 2 == 1 and self.end % 2 == 1):
print ( self.start + self.end ) / 2
elif self.start % 2 == 1 or self.end % 2 == 1:
tmp_num = ( self.start + self.end + 1) / 2
print tmp_num - 1, tmp_num a = lis(1,10)
b = lis(1,9)
c = lis(2,10)
d = lis(2,9)
a.test()
b.test()
c.test()
d.test()