<python>class

 之前在学习神经网络,在调用现成的包时有时想对它进行一些修改,这就要用到Python的类继承,所以先来学下Python中类的定义和继承

class Example():
    def __init__(self,parameter1,parameter2,...,parametern):
        self.parameter1 = parameter1
        self.parameter2 = parameter2
        ………………
        //这一项是在之后调用class时将传递过来的参数赋给class内的元素
        //self代表这个对象
    def function1(self):
        print(self.parameter1)
        //之后定义的函数都是以self为参数,如果要调用self内的变量,就用self.parameter的形式

A = Example(a1,a2,...,an)
//之后如果需要创造一个example类的函数,就用这种形式来调用,并传递给它初始值

print(A.parameter1)
//如果要使用A内的变量,就用这种格式
A.function1()
//要调用A内的函数,就用这种方式


一个具体的例子:
class Car():
    def __init__(self, make, model, year):
        self.make = make    
        self.model = model
        self.year = year
    def get_descriptive_name(self):
        long_name = str(self.year) + ' ' + self.make + ' ' + self.model
        return long_name.title()
    def fill_gas_tank():
        print("We have filled the gas tank.")

my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())


如果是继承类,这个直接拿个例子来说吧
class ElectricCar(Car):     //把父类名当参数
    //如果不需要新增attribute的话
    def __init__(self,make,model,year):
        super(ElectricCar,self).__init__(make,model,year)
    //如果需要新增attribute的话,就把attribute加到init的参数里,然后用常规方法添在super下面就好
    def __init__(self,make,model,year,money):
        super(ElectricCar,self).__init__(make,model,year)
        self.money = money
    //如果需要override父类中的method,就定义一个同名的函数
    def fill_gas_tank():
        print("This car doesn't need a gas tank!")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值