面向对象编程基础
定义类并创建实例
class Person(object):
pass
xiaoming = Person()
xiaohong = Person()
print xiaoming
print xiaohong
print xiaoming == xiaohong
创建实例属性
class Person(object):
pass
p1 = Person()
p1.name = 'Bart'
p2 = Person()
p2.name = 'Adam'
p3 = Person()
p3.name = 'Lisa'
L1 = [p1, p2, p3]
L2 = sorted(L1,lambda x,y:cmp(x.name,y.name))
print L2[0].name
print L2[1].name
print L2[2].name
初始化实例属性
class Person(object):
def __init__(self,name,gender,birth,job):
self.name = name
self.gender = gender
self.birth = birth
self.job = job
xiaoming = Person('Xiao Ming', 'Male', '1990-1-1', job='Student')
print xiaoming.name
print xiaoming.job
访问限制
class Person(object):
def __init__(self, name, score):
self.name = name
self.__score = score
p = Person('Bob', 59)
print p.name
print p.__score
创建类属性
class Person(object):
count = 0
def __init__(self,name):
Person.count = Person.count + 1
self.name = name
p1 = Person('Bob')
print Person.count
p2 = Person('Alice')
print Person.count
p3 = Person('Tim')
print Person.count
定义实例方法
class Person(object):
def __init__(self, name, score):
self.name = name
self.__score = score
def get_grade(self):
if(self.__score < 60):
return "C"
elif(self.__score >= 90):
return "A"
else:
return "B"
p1 = Person('Bob', 90)
p2 = Person('Alice', 65)
p3 = Person('Tim', 48)
print p1.get_grade()
print p2.get_grade()
print p3.get_grade()
定义类方法
class Person(object):
__count = 0
@classmethod
def how_many(cls):
return cls.__count
def __init__(self,name):
self.name = name
Person.__count = Person.__count + 1
print Person.how_many()
p1 = Person('Bob')
print Person.how_many()