python类和对象

class

类的定义

class Cat(object):
    def __init__(self,name,age): # 相当于Java的构造函数
        self.name=name
        self.age=age
        print("__init__方法")
    
    def __str__(self):  # 相当于Java的toString方法
        pass
    
    def eat(self):
        print("eat......")
        
    def drink(self):
        print("drink......")

tom=Cat("jack",10) # 创建了tom对象,python会自动的调用__init__()方法

__del__():
class Cat(object):
    """docstring for test"""
    def __init__(self,name,age):
        self.name=name
        self.age=age
        print("__init__被调用")

    def __del__(self):
        print("__del__")

tom=Cat("name",12)
del tom
print("=" * 30)
Out:
__init__被调用
__del__
==============================

tom=Cat("name",12)
print("=" * 30)
Out:
__init__被调用
==============================
__del__

魔法方法

在python中,所有的以”__”双下划线包起来的方法,都被统称为”魔法方法”。例如上述的__init____str__

魔法方法参考

私有属性和方法

  • Python中没有像Java中有public和private这些关键字来区别公有属性和私有属性
  • Python是以属性命名方式来区分,如果在属性名前面加了2个下划线’__’,则表明该属性是私有属性,否则为公有属性(方法也是一样,方法名前面加了2个下划线的话表示该方法是私有的,否则为公有的)。

继承

class Animal:
    def eat(self):
        print("-----吃----")
    def run(self):
        print("-----跑----")

class Dog(Animal):     # python继承关键 
    def bark(self):
        print("----汪汪叫---")
    def run(self):        # 重写
        super().run()   # 调用被重写的父类的方法

dog = Dog()
dog.eat()

上述介绍的私有属性和方法不能被继承。

多继承

class Base(object):
    def test(self):
        print("----Base")

class A(Base):
    def test1(self):
        print("-----test1")

class B(Base):
    def test2(self):
        print("-----test2")

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

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

注意如果父类拥有同名的方法,子类会调用哪个方法:

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
    #def test(self):
    #    print("-----C")


c = C()
c.test() # -----A

print(C.__mro__) # (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.Base'>, <class 'object'>) 如果有同名方法,会按这个顺序执行。其中<class '__main__.A'>, <class '__main__.B'>这个顺序与class C(A,B)这个顺序有关。

多态

多态的概念是应用于Java和C#这一类强类型语言中,而Python崇尚“鸭子类型”。

所谓多态:定义时的类型和运行时的类型不一样,此时就成为多态。

class Dog(object):
    def print_self(self):
        print("大家好,我是dog,...")

class xiaogou(Dog):
    def print_self(self):
        print("hello ,我是xiaogou")


def introduce(temp):
    temp.print_self()


dog1 = Dog()
dog2 = xiaogou()

introduce(dog1)
introduce(dog2)

类属性、实例属性

class Tool(object):

    #类属性
    num = 0

    #方法
    def __init__(self, new_name):
        #实例属性
        self.name = new_name
        #对类属性+=1
        Tool.num += 1


tool1 = Tool("t1")
tool2 = Tool("t2")
tool3 = Tool("t3")

print(Tool.num)

静态方法、类方法

class Game(object):

    #类属性
    num = 0

    #实例方法 操作实例属性
    def __init__(self):
        #实例属性
        self.name = "laowang"

    #类方法  操作类属性
    @classmethod
    def add_num(cls):
        cls.num = 100

    #静态方法  不操作类属性和实例属性
    @staticmethod
    def print_menu():
        print("----------------------")

game = Game()
#Game.add_num()#可以通过类的名字调用类方法
game.add_num()#可以通过这个类创建出来的对象调用这个类方法
print(Game.num)

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

单例模式

class Car(object):
    __instance=None

    def __init__(self):
        pass

    def __new__(cls):
        if not cls.__instance:
            cls.__instance=object.__new__(cls)

        return cls.__instance


c1=Car()
c2=Car()

print(id(c1))
print(id(c2)) #相等

《python类和对象》

    原文作者:逝水无痕
    原文地址: https://segmentfault.com/a/1190000014241159
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞