Python面向对象编程基础

面向对象编程基础



定义类并创建实例


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()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值