Learning python - Day supplement - Object Oriented

Learning python - Day supplement - Object Oriented

python private --name mangling (name changes, name)

When naming, by using two underscores as the beginning, you can make the variable programming function or private, but this is actually a pseudo-private python, python actually carried out by modifying the name, this will python named variables or functions changed the name of the class name __ _ variable name

class A:
    __name="hello"

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

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

inherit

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("太撑了,吃不下了!")

Guess you like

Origin www.cnblogs.com/alking1001/p/11616177.html