python类笔记

python类笔记

私有属性和方法

命名前加两个下划线

1
from module import *

这样做无法直接调用module中的__func()方法,但直接import却是可以的

1
from module import __func

抽象方法

@abstractmethod

__new__和__init__

__init__() 方法用于给属性赋值,不可以有返回值,__new__()多用于构造不可变对象,必须有返回值,返回实例对象。构建新实例的时候,先调用__new__()初始化一个实例,然后调用__init__() 进行属性赋值。

super

当子类重写父类构造方法时,为了避免父类属性没有初始化,有两种方式,第一种直接调用父类方法

1
2
3
4
5
6
7
8
9
10
class A(object):
def __init__(self):
print("init attr of A")


class B(A)
def __init__(self):
print("init attr of A")
A.__init__(self)
print("init attr of B")

也可以直接用super()方法

1
2
3
4
5
6
7
8
9
10
class A(object):
def __init__(self):
print("init attr of A")


class B(A)
def __init__(self):
print("init attr of A")
super().__init__()
print("init attr of B")

self和cls

实例方法参数需要带self,而类方法需要带cls

继承内置对象

继承dict类型,重写__getitem__()方法

1
2
3
4
5
6
7
8
9
10
11
12
class SeqDict(dict):

def __getitem__(self, item):

if len(item) != 2:
return dict.__getitem__(self, item)
else:
a, b = item
try:
return dict.__getitem__(self, (a[-1:], b[:1]))
except TypeError:
raise BaseException("SeqDict TypeError in: " + str(item))

继承不可变长对象(实现了__immutable__()方法),重写tuple

1
2
3
4
class Seq(tuple):

def __new__(cls, *args, **kwargs):
return super(Seq, cls).__new__(cls, args)

静态方法

@staticmethod