类的基本使用
class Cat(object):
"""docstring for Cat"""
def __init__(self, arg):
super(Cat, self).__init__()
self.arg = arg
def year(self):
print(self.arg)
def action(self):
首先__init__是创建类必须带的,使用sublimetext创建类时,会自动填充
其次所有方法必须默认传递self,其实就是java的this,只不过java是编译器给加上的
创建示例及调用:
f = Cat('qqqqqqqqqqq')
print(f.arg)
f.year()
其余调用方式与java c++类似
类的继承:
Python 2.7中继承写法:
class Car(object):
def __init__(self, make, model, year):
--snip--
class ElectricCar(Car):
def __init__(self, make, model, year):
super(ElectricCar, self).__init__(make, model, year)
--snip--
Python3.0继承写法:
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""初始化父类的属性"""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
导入单个类:
from car import Car
导入多个类:
from car import Car, ElectricCar
导入整个模块:
import car
导入模块中所有类:
from module_name import *
一个模块中导入另一个模块(一个模块类实现依赖于另一个模块):
from car import Car