您的位置:首页 > 编程语言 > Python开发

<python>class

2017-01-14 16:13 232 查看
 之前在学习神经网络,在调用现成的包时有时想对它进行一些修改,这就要用到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!")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: