python——类(一)

1〉首先,怎么写一个类,用个例子

class Student(object):
    def __init__(self,name,score,gender):
        self.__name=name
        self.__score=score
        self.__gender=gender
    def get_name(self):
        return self.__name
    def print_score(self):
        print('%s:%s'%(self.__name,self.__score))
    def set_score(self,score):
        if 0<=score<=100:
            self.__score=score
        else:
            raise ValueError('bad score')
    def get_grade(self):
        if self.__score>=90:
            return 'A'
        elif self.__score>=60:
            return 'B'
        else:
            return 'C'
    def get_gender(self):
        if self.__gender=='男':
            return 'man'
        elif self.__gender=='女':
            return 'woman'

需要注意的点:

类名后面的(object)是可以忽略的。(只有当子类继承父类的时候,类名后面的括号里面是父类的名字,下面会有例子)

def __init__(self){}这个类似构造函数,init前后分别有两个下划线,一共有四个下划线,括号里面的self是必写的一个,但是不会用到它(我个人的理解是this,仅仅个人认为)

特别注意get和set方法,和jsp中的方法也类似。


2〉以上仅仅是一个类,下面讲讲类的继承和多态:

class Animal(object):
    def run(self):
        print('Animal is running...')
class Dog(Animal):
    def run(self):
        print('Dog is running...')
class Cat(Animal):
    def run(self):
        print('Cat is running...')
def run_twice(animal):
    animal.run()

如上代码中Animal是父类,Dog和Cat都是Animal的子类,通过在类名后面+(父类的类名)实现

def run_twice(animal):
    animal.run()
其中,这个函数是实现多态的

>>> run_twice(Animal())
Animal is running...
>>> run_twice(Dog())

Dog is running...

这个是 调用的结果


3〉了解类属性和实例属性:简单的说 类属性是在类中直接写的属性,实例属性指在类外重写的属性。一般,先看有没有实例属性,再看有没有类属性。

class CocaCola(object):
    calories=140
    sodium=45
    total_carb=39
    caffeine=34
    def __init__(self,logo_name):
        self.logo_name=logo_name
    def drink(self):
        print('You got{}cal energy!'.format(self.calories))
class zeroCola(CocaCola):
    calories=0
>>> coke_a.drink()

You got0cal energy!

子类会覆盖父类中相同的属性的值。


4〉认识除了__init__之外的内置函数

class Employee:
    '所有员工的基类'
    empCount=0
    def __init__(self,name,salary):
        self.name=name
        self.salary=salary
        Employee.empCount+=1
    def displayCount(self):
        print ("Total Employee %d"% Employee.empCount)
    def displayEmployee(self):
        print("Name:",self.name,"Salary:",self.salary)
print("Employee.__doc__:",Employee.__doc__)
print("Employee.__name__:",Employee.__name__)
print("Employee.__module__:",Employee.__module__)
print("Employee.__bases__:",Employee.__bases__)
print("Employee.__dict__:",Employee.__dict__)

结果如下:

Employee.__doc__: 所有员工的基类
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)

Employee.__dict__: {'__weakref__': <attribute '__weakref__' of 'Employee' objects>, 'displayCount': <function Employee.displayCount at 0x0000000003570F28>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__module__': '__main__', '__init__': <function Employee.__init__ at 0x0000000003570EA0>, 'empCount': 0, 'displayEmployee': <function Employee.displayEmployee at 0x0000000003565048>, '__doc__': '所有员工的基类'}

#****************************************************************************

除此之外,我还找到一些

类的专有方法:

  • __init__ : 构造函数,在生成对象时调用
  • __del__ : 析构函数,释放对象时使用
  • __repr__ : 打印,转换
  • __setitem__ : 按照索引赋值
  • __getitem__: 按照索引获取值
  • __len__: 获得长度
  • __cmp__: 比较运算
  • __call__: 函数调用
  • __add__: 加运算
  • __sub__: 减运算
  • __mul__: 乘运算
  • __div__: 除运算
  • __mod__: 求余运算
  • __pow__: 乘方
注意的是:这些都是私有的,外部不能调用。
  • 4
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值