面向对象

分析类 创建一个对象

类是对象的模块
对象是类的具体实例

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

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

class DanJia():
    def __init__(self,count):
        self.count = count

class ZiDan():
    def __init__(self,name,sh):
        self.name = name
        self.sh = sh
laowang = Person("老王")
M4 = Gun("M416")
dj = DanJia(40)
for i in range(40):
    zd = ZiDan("5.56",5)

*类的魔法方法 共有四种

init() 创建对象,并返回引用
str() 初始化属性
del() 打印对象调用,有返回值
new() 删除对象调用

私有属性和方法用两个下划线来表示

*私有属性

class Dog():
    def __init__(self):
        self.name = ""
        self.__age = 0#私有属性
    
    def sleep(self):
        print("sleep")

    def setAge(self,age):
        if age > 15 or age < 1:
            print("年龄不符合")
        else:
            self.__age = age

    def getAge(self):#公有方法
        return self.__age


hsq = Dog()
#print(hsq.__age)#不能直接获取了
#print(hsq.getAge())#必须通过共有方法获取

#hsq.__age = 100#就是一个普通属性
hsq.setAge(10)
print(hsq.getAge())

*私有方法

class QQ():
   
    def __openvip(self):
        print("开会员成功")

    def checkqq(self,money):
        if money > 10:
            self.__openvip()
        else:
            print("不能开")
         


qq = QQ()
qq.checkqq(12)
#qq.openvip()

qq1 = QQ()
qq1.checkqq(10)

单继承和多继承

*单继承

class Animal():
    pass


class Cat(Animal):
    def __init__(self,name):
        self.name = name

class Dog(Animal):
    def __init__(self,name):
        self.name = name


bsm = Cat("波斯猫")
print(bsm.name)

wc = Dog("旺财")
print(wc.name)

*多继承

class A():
    def __init__(self):
        self.name = 10
        self.age = 20

    def show(self):
        print("heheh A")
class B():
    def show1(self):
        print("哈哈哈")


class C(A,B):
    pass


c = C()
print(c.name)
print(c.age)
c.show()
c.show1()
print(c.age)
print(C.__mro__)

还有多态和静态的方法

@classmethod 类的方法
@staticmethod 静态方法

你可能感兴趣的:(面向对象)