面向对象-2

隐藏属性

class Dog:
    def set_age(self,new_age):
        if new_age > 0  and new_age <=100:
            self.age = new_age
        else:
            self.age = 0
    def get_age(self):
        return self.age
dog = Dog()
dog.set_age(-10)
age = dog.get_age()
print(age)

私有方法

class Dog:
    #私有方法
    def __send_msg(self):
        print("----正在发送短信----")
    #公有方法
    def send_msg(self,new_money):
        if new_money > 1000:
            self.__send_msg()
        else:
            print("余额不足,请先充值再发送短信")

dog = Dog()
dog.send_msg(10000)

 

__del__方法

class Dog:
    def __del__(self):
        print("----英雄over----")
dog1 = Dog()
dog2 = dog1
del dog1 #只有这一行时,先打印==,再打印over,==后没有代码,才删除引用
del dog2 #有这行时,引用会被先删除完,才打印==
print("================")

 

对象的引用个数 

import sys
class T:
    pass

t = T()
print(sys.getrefcount(t)) #getrefcount(),测量一个对象引用计数时引用必须要存在一个。getrefount()还会自己占用一个。

tt = t
print(sys.getrefcount(tt))

 

继承class Animal:

def eat(self):
        print("---吃---")
    def drink(self):
        print("---喝---")
    def sleep(self):
        print("---睡觉---")
    def run(self):
        print("---跑---")
class Dog(Animal):
    def bark(self):
        print("---汪汪叫---")
class Cat(Animal):
    def catch(self):
        print("---抓老鼠---")

class Xiaotq(Dog):
    def fly(self):
        print("---飞---")
wangcai
= Dog() wangcai.eat() xtq = Xiaotq() xtq.fly() xtq.bark() xtq.eat()

重写

class Animal:
    def eat(self):
        print("---吃---")
    def drink(self):
        print("---喝---")
    def sleep(self):
        print("---睡觉---")
    def run(self):
        print("---跑---")
class Dog(Animal):
    def bark(self):
        print("---汪汪叫---")
class Cat(Animal):
    def catch(self):
        print("---抓老鼠---")

class Xiaotq(Dog):
    def fly(self):
        print("---飞---")
    def bark(self): #此处重写父类bark()方法
        print("---狂叫---")

wangcai = Dog()
wangcai.eat()

xtq = Xiaotq()
xtq.fly()
xtq.bark() #---狂叫---,调用自己的,非父类的
xtq.eat()

调用被重写的方法

class Animal:
    def eat(self):
        print("---吃---")
    def drink(self):
        print("---喝---")
    def sleep(self):
        print("---睡觉---")
    def run(self):
        print("---跑---")
class Dog(Animal):
    def bark(self):
        print("---汪汪叫---")
class Cat(Animal):
    def catch(self):
        print("---抓老鼠---")

class Xiaotq(Dog):
    def fly(self):
        print("---飞---")
    def bark(self):
        print("---狂叫---")
        #第1种调用被重写父类的方法
        # Dog.bark(self) #调用父类的bark(),self必须传
        #第2种
        super().bark()
wangcai = Dog()
wangcai.eat()

xtq = Xiaotq()
xtq.fly()
xtq.bark() #---狂叫---,调用自己的,非父类的
xtq.eat()

私有方法、私有属性在继承中的表现

如果调用的是继承父类中的公有方法,可以在这个公有方法中访问父类中的私有属性和私有方法

但是如果在子类中实现了一个公有方法,那么这个方法不能够调用继承的父类中的私有方法和私有属性

class A:
    def __init__(self):
        self.num1 = 100
        self.__num2 = 200
    def test1(self):
        print("---test1---")
    def __test2(self):
        print("---test2---")
    def test2(self):
        self.__test2()
        print(self.__num2)
    def test3(self):
        self.__test2()
        print(self.__num2)
class B(A):
    def test4(self):
        self.__test2()
        print(self.num2)

b = B()
b.test1()
# b.__test1() #私有方法不会被继承
print(b.num1)
# print(b.__num2) #私有属性不能被继承
b.test3()
b.test4() #调用报错

 

继承

class Base(object): #新式类
    def test(self):
        print("---Base")
class A(Base):
    def test1(self):
        print("---A")
class B(Base):
    def test2(self):
        print("---B")

class C(A,B): #继承多个父类
    def test(self):
        print("---V")

c = C()
c.test()
c.test1()
c.test2()

 

多继承搜索顺序

class Base(object): #新式类
    def test(self):
        print("---Base")
class A(Base):
    def test(self):
        print("---A")
class B(Base):
    def test(self):
        print("---B")

class C(A,B): #继承多个父类
    pass

c = C()
c.test()
print(C.__mro__)  #调用test()方法时,搜索的顺序,如果在某个类中找到了方法,就停止搜索

 

类属性和实例属性

实例属性:和具体的某个实例对象有关系,并且一个实例对象和另个一个实例对象不能共享属性

类属性:类属性属于类对象,并且多个实例对象之间共享同一个类属性

__init__方法在类中也只存在一份,每个实例对象中存有__init__方法的引用

class Tool(object):
    #类属性
    num = 0
    #方法
    def __init_(self, new_name):
        #实例属性
        self.name = new_name
        #调用类属性
        Tool.num += 1
        
tool1 = Tool("铁锹")
tool2 = Tool("工兵铲")

 

实例方法,类方法、静态方法

class Game(object):
    #类属性
    num = 0
    #实例方法,必须有self参数
    def __init__(self):
        #实例属性
        self.name = "laowang"

    #类方法,需要有cls参数
    @classmethod
    def add_num(cls):
        cls.num = 100

    #静态方法,可以没有参数
    @staticmethod
    def print_menu():
        print("-------------------------")
        print(" 穿越火线V11.1 ")
        print(" 1.开始游戏")
        print(" 2.结束游戏")
        print("-------------------------")

game = Game()
#Game.add_num() #通过类名调用类方法
game.add_num() #类的实例调用类方法
print(Game.num)

# Game.print_menu() #通过类调用静态方法
game.print_menu() #通过实例对象调用静态方法

 

设计4S类

class CarStore(object):
    def __init__(self):
        self.factory = Factory()

    def order(self,car_type):
        return self.factory.select_car_by_type(car_type)

class Factory(object):
    def select_car_by_type(self,car_type):
        if car_type == "索纳塔":
            return Sonata()
        elif car_type == "名图":
            return Mingtu()


class Car(object):
    def move(self):
        print("车在移动...")
    def music(self):
        print("正在听音乐...")
    def stop(self):
        print("车在停止...")

class Sonata(Car):
    pass
class Mingtu(Car):
    pass


car_store = CarStore()
car = car_store.order("索纳塔")
car.move()
car.music()
car.stop()

工厂方法模式

class Store(object):
    def select_car(self): #共有功能放基类中,但不实现,由子类实现
        pass

    def order(self,car_type):
        return self.select_car(car_type)

class BMWCarStore(Store): #子类继承父类的select_car和order方法,
    # 继承完了后order方法调用子类本身的select_car方法
    def select_car(self,car_type):
        return BMWFactory().select_car_ty_type(car_type)


class CarStore(Store):
    def select_car(self,car_type):
        return Factory().select_car_ty_type(car_type)

class BMWFactory(object):
    def select_car_by_type(self,car_type):
        if car_type == "X1":
            return X1()
        elif car_type == "320li":
            return X6()
class Factory(object):
    def select_car_by_type(self,car_type):
        if car_type == "索纳塔":
            return Sonata()
        elif car_type == "名图":
            return Mingtu()


class Car(object):
    def move(self):
        print("车在移动...")
    def music(self):
        print("正在听音乐...")
    def stop(self):
        print("车在停止...")

class Sonata(Car):
    pass
class Mingtu(Car):
    pass
class X1():
    pass
class X6():
    pass


car_store = CarStore()
car = car_store.order("索纳塔")
car.move()
car.music()
car.stop()

bmw_store =BMWCarStore()
bmw = bmw_store.order("X6")

 

__new__方法

class Dog(object):
    def __init__(self):
        pass
    def __del__(self):
        pass
    def __str__(self):
        return "对象的描述信息"
    def __new__(cls): #cls此时是Dog指向那个类对象
        print("----new方法----")
        return object.__new__(cls) #重写了父类方法,必须调用父类的new方法,不然创建对象不成功。

#1.调用__new__方法创建对象,找一个变量来接收__new__的返回值,这个返回值表示创建出来的对象的引用,负责创建
#2.__init__(刚刚创建出来的对象的引用),负责初始化
#3.返回对象的引用
xtq = Dog()

 

创建单例对象

class Dog(object):
    __instance = None
    def __new__(cls):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance #上一次创建的对象

a = Dog()
b = Dog()
print(id(a))
print(id(b))

 

只初始化一次对象1

class Dog(object):
    __instance = None
    def __new__(cls,name):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance #上一次创建的对象

    def __init__(self, name):
        self.name = name

a = Dog("旺财")
print(a.name)
b = Dog("哮天")
print(b.name)
print(id(a))
print(id(b))

只初始化一次对象2

class Dog(object):
    __instance = None
    __init_flag = False
    def __new__(cls,name):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance #上一次创建的对象

    def __init__(self, name):
        if Dog.__init_flag == False:
            self.name = name
            Dog.__init_flag = True


a = Dog("旺财")
print(a.name)
b = Dog("哮天")
print(b.name)
print(id(a))
print(id(b))

 

posted @ 2020-03-18 00:03  红色天空下  阅读(127)  评论(0)    收藏  举报