#python杂记,写一写,以后忘了,方便回来看吧
#一:类的继承
与C++中继承不同,python中使用括号包括基类
C++:
class base_class /*父类*/
{
private:
public:
protected:
}
class sub_class:inherit_way base_class /*inherit_way继承方式*/
{
}
python:
class base_class:
def __init__(self,name="",age=0):#初始化类时自动执行
self.__name=name #带有__私有
self.age=age #age非私有
def __fun():#定义私有方法
......
class inherit(base_class):#继承对象放在括号里面
def __init__(self,name,age):
base_class.__init__(self,name,age)#继承中,构造函数不会自动调用,要手动执行
#上面init可以用下面的super代替
#super(inherit,self).__init__(name,age)#super为内置函数
#如果在派生类中找不到方法,才会去基类里找
python中如果要强制访问私有属性,可以通过类下:
class base:
def __init__(self,name,age):
self.__name=name
self.age=age
#以下为测试
>>> test=base("shui",10)
>>> print(test.age)
10
>>> print(test.__name)#错误
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
print(test.__name)
AttributeError: 'base' object has no attribute '__name'
>>> print(test._base__name)#
shui
>>>