类
定义类
class ClassName:
'''类的帮助信息'''
statement
创建类实例
ClassName(parameterlist)
创建__init__()方法
class Geese:
'''大雁类'''
def __init__(self, beak, wing, claw):
print("我是大雁类")
print(beak)
print(wing)
print(claw)
wildGoose = Geese(beak1, wing1, claw1)
创建类成员并访问
创建实例方法并访问
def functionaName(self, parameterlist):
block
instanceName.functionName(parametervalue)
创建数据成员并访问
类属性:
在所有实例间共享
>>> class Geese:
... '''雁类'''
... neck = "abcd"
... wing = "efgh"
... number = 0
... def __init__(self):
... Geese.number += 1
... print(Geese.number)
...
>>> list1 = []
>>> for i in range(4):
... list1.append(Geese())
...
1
2
3
4
>>> print(Geese.number)
4
>>>
动态添加类属性:
>>> Geese.beak = "ijkl"
>>> print(list1[1].beak)
ijkl
>>>
实例属性:
只作用于当前实例
>>> class Geese:
... '''雁类'''
... def __init__(self):
... self.neck = "abcd"
... self.wing = "efgh"
... print(self.neck)
... print(self.wing)
...
>>> geese1 = Geese()
abcd
efgh
>>>
动态修改实例属性
>>> geese1.neck = "ijkl"
>>> geese1.neck
'ijkl'
>>>
访问限制
保证某些属性或方法不被外部访问
foo:首尾双下划线,定义特殊方法一般是系统定义名字
__foo:表示private成员,只允许定义该方法的类本身进行访问
>>> class Swan:
... '''天鹅'''
... __neck_swan = "abcd"
... def __init__(self):
... print(Swan.__neck_swan)
...
>>> swan1 = Swan()
abcd
>>> print(swan1._Swan__neck_swan) #通过实例名._类名__XXX的方式访问
abcd
>>> print(swan1.__neck_swan)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Swan' object has no attribute '__neck_swan'
>>>
属性
与类属性和实例属性不同
创建用于计算的属性
通过@property(装饰器)将方法转换为属性,可以直接通过方法名访问,而无须再添加小括号
@property
def methodname(self)
block
例:
>>> class Rect:
... def __init__(self, width, height):
... self.width = width
... self.height = height
... @property
... def area(self):
... return self.width*self.height
...
>>> rect1 = Rect(800 , 600)
>>> rect1.area
480000
>>>
为属性添加安全保护机制
想要创建一个可以被读取,但是不能被修改的属性,使用@property
>>> class TVshow:
... def __init__(self, show):
... self.__show = show
... @property
... def show(self):
... return self.__show
...
>>> tvshow = TVshow("abcdefg")
>>> print(tvshow.show)
abcdefg
>>>
继承
基本语法
class ClassName(baseclasslist):
'''类的帮助信息'''
statement
例:
>>> class Fruit:
... color = "green"
... def harvest(self, color):
... print(color)
...
>>> class Apple(Fruit):
... color = "red"
... def __init__(self):
... print("I am apple")
...
>>> apple1 = Apple()
I am apple
>>> apple1.harvest(apple1.color)
red
>>>
方法重写
可以在派生类中重写harvest()方法
>>> class Apple(Fruit):
... color = "red"
... def __init__(self):
... print("I am apple")
... def harvest(self, color):
... print("I do not like " + color)
...
>>> apple2 = Apple()
I am apple
>>> apple2.harvest(apple2.color)
I do not like red
派生类中调用基类__init__()方法
如果想要再派生类中调用基类的__init__()方法进行初始化,需要再派生类中使用super()函数
super().__init__()
例:
>>> class Fruit:
... def __init__(self, color = "green"):
... Fruit.color = color
... def harvest(self, color):
... print(self.color)
...
>>> class Apple(Fruit):
... color = "red"
... def __init__(self):
... print("I am apple")
... super().__init__()
...
>>> apple3 = Apple()
I am apple
>>> apple3.harvest(apple3.color)
red
>>>