python学习-第四天补充-面向对象

python学习-第四天补充-面向对象

python 私有 ——name mangling(名字修改、名字)

在命名时,通过使用两个下划线作为开头,可以使得这个变量或者函数编程私有的,但是这个其实的python的伪私有,实际是python通过名字修改来进行的,python会把这样命名的变量或者函数名改为_类名__变量名

class A:
    __name="hello"

t = A();
#print(t.__name)
#这样会出现错误,错误提示说这个变量没有__name类型

print(t._A__name)
#这里python实际是给__name改名为_A__name了

继承

import random as r
class fish:
    def __init__(self):
        self.x = r.randint(0, 10)
        self.y = r.randint(0, 10)
    def move(self):
        self.x -= 1
        print("我的位置是:", self.x, self.y)


class godfish(fish):
    pass


class shark(fish):
    def __init__(self):
        #fish.__init__(self) 这里是调用未绑定的父类方法
        super().__init__() #使用super函数,和上面的方式一样,但是更简单
        self.hungry = True


def eat(self):
    if self.hungry:
        print("我要吃饭了")
        self.hungry = False
    else:
        print("太撑了,吃不下了!")

猜你喜欢

转载自www.cnblogs.com/alking1001/p/11616177.html