Python之面向对象

目录

一、类的定义

二、魔法方法

三、属性管理

四、封装

五、继承&多态


一、类的定义

 


# 类封装
class Dog:
    name="修狗"
    age=3

d=Dog()
print(f'name is {d.name} ,age is {d.age}')
# python与java关于类封装的区别
d.sex="母"
print(f'name is {d.name} ,age is {d.age} ,sex is {d.sex}')
print("==============================")

 

# 构造函数
class Dog:
    name="修狗"
    age=3

 

 

class Dog:
   
 # 法1
 def __init__(self,name,age):  #self相当于java的this
     self.name=name
     self.age=age

d=Dog("哈士奇",7)

print(f'name is {d.name} ,age is {d.age}')

 

 

# 构造函数
class Dog:

 # # 法2
    def __init__(self,*args,**kwargs):  # self相当于java的this
       if kwargs.get("name")!=None:
           self.name=kwargs.get("name")
       if kwargs.get("age")!=None:
           self.age=kwargs.get("age")

d=Dog(name="huhu",age=12)
print(f'name is {d.name} ,age is {d.age}')

 


二、魔法方法

 

# 魔法方法
# init 被用于初始化实例对象,new方法创建对象后就会调用该方法对实例的属性进行初始化。
class Dog:
    def __init__(self, name: str = "小黄", age: int = 12):
        self.name = name
        self.age = age


# d = Dog()  # 不会报错
# d = Dog(name="小白")  # 不会报错
d = Dog(name="小黑", age=20)
# d = Dog(name=20, age="小黑") #报错
print(d)
print(f'name is {d.name};age is {d.age}')
print("==========================================")
#del 是析构方法,当对象的引用计数变为0时,这个对象会被销毁掉,此时就会调用del方法
class T:
    def __del__(self):
        print("对象被销毁")


t = T()
# t指向0,此前创建的T的实例被销毁
print("1111")
t = 0
print("2222")
print("==========================================")
# call 允许一个类的实例像函数一样被调用,这是一个非常重要的特性
class T:
    def __call__(self, *args, **kwargs):
        print("类的实例可以像函数一样被调用")


t = T()
t()  # 相当于执行__call__方法体中的内容
print("==========================================")
# len 是内置函数,len(t) 会调用实例的 **len** 方法
class T:
    def __len__(self):
        return 110


t = T()
print(len(t))
# 当被 str() 调用时, 调用该 **str** 方法
print("==========================================")
class Tu:
    def __str__(self):
        return f"我是{Tu.__name__}的一个实例"


t = Tu()
print(t)
print("==========================================")
# bool 可用于逻辑判断部分
class T:
    def __init__(self, age):
        self.age = age

    def __bool__(self):
        return self.age > 18


print(bool(T(17) and T(19)))

print("==========================================")

# 比较部分
class Student:
    def __init__(self, age):
        self.age = age

    def __lt__(self, other):
        return self.age < other.age

    def __eq__(self, other):
        return self.age == other.age

# 对象之间是没有可比性的 less than-->小于 grant than -->大于
s1 = Student(3)
s2 = Student(4)
print(s1 < s2)
print(s1 == s2)#比较的是数值  相当于java里的“equals”
print(s1 is s2) #比较的是地址 相当于java里的“==”


print("==========================================")
# 字典就是实现了这三个魔法方法,才提供了以[]为基础的操作class MyData:
class MyData:
    def __init__(self, data=None):
        if data is None:
            data = dict()
        self.data = data

    def __getitem__(self, item):
        return self.data.get(item)

    def __setitem__(self, key, value):
        self.data[key] = value

    def __delitem__(self, key):
        del self.data[key]


my_data = MyData()
my_data['name'] = '小刚'
my_data['age'] = 14
print(my_data['name'])
print(my_data['age'])

print("==========================================")
# 如果一个对象实现了 iter , 那么它就是一个可迭代对象
# 如果既实现 iter 又实现 next ,那么它就是一个迭代器
#
class Color(object):
    def __init__(self):
        self.index = -1
        self.colors = ['red', 'white', 'black', 'green']

    def __iter__(self):
        self.index = -1
        return self

    def __next__(self):
        self.index += 1
        if self.index >= self.colors.__len__():
            raise StopIteration
        return self.colors[self.index]


color_object = Color()
# 遍历输出所有颜色
for color in color_object:
    print(color)

 


三、属性管理

class Plane(object):
    category = '飞机'
    def fly(self):
      print("哈哈哈哈哈")

p1, p2 = Plane(), Plane()
# print(p1.category, p1.category)
# Plane.category = '拖拉机'
# print(p1.category, p2.category)
print(p1.category, p1.category)
p1.category = '拖拉机'
print(p1.category, p2.category)
print("=================================")
# 这里主要涉及到了类属性与对象属性实例属性的区别
p1.name = 'sa'
p1.__dict__['pwd'] = '123'
print(p1.__dict__)  #对象属性实例属性
print(Plane.__dict__) #类属性

print("=================================")
# 例题1
class Dog:
    name: str = '小黑'
    age: int = 3


d1 = Dog()
d1.name = "大黄"
d2 = Dog()
Dog.name = "小白"
print(d1.name)
print(d2.name)

 


 

四、封装

 

class Stu:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def get_name(self):
        return self.__name

    def set_name(self, name):
        self.__name = name

    def get_age(self):
        return self.__age

    def set_age(self, age):
        self.__age = age


stu1 = Stu('小明', 14)
stu2 = Stu('小红', 14)
print(stu1.get_name(), stu1.get_age())
print(stu2.get_name(), stu2.get_age())

 

 

class Book:
    def __init__(self, price):
        self._price = price

    @property
    def price(self):
        return self._price

    # 如果你希望可以对price进行赋值,那么需要用 @ price.setter装饰器再装饰一个方法,该方法完成对 _price
    # 属性的赋值操作。
    @price.setter
    def price(self, price):
        if price > 0:
            self._price = price
        else:
            raise Exception('价格不能为负数')


book = Book(58.5)
print(book.price)
# book.price = -1
book.price = 1
print(book._price)

 

 

 

 方法拓展
 类方法 : 可以通过类名调用的方法
加上注解,修改参数为 cls (当前类),可以通过 cls 调用类的属性
静态方法 : 可以通过类名与对象来调用,但是无法使用类变量

 

# class Book:
#     @classmethod
#     def run(cls):
#         print(cls.__name__)
#
#     # @staticmethod
#     # def say(cls):
#     #     print(cls.__name__)   #报错
#     #     print("hello world")
#     @staticmethod
#     def say():
#         print("hello world")
#
#     def __init__(self, price):
#         self._price = price
#
#     @property
#     def price(self):
#         return self._price
#
#     @price.setter
#     def price(self, price):
#         if price > 0:
#             self._price = price
#         else:
#             raise Exception('价格不能为负数')
#
#
# book = Book(58.5)
# print(book.price)
# # book.price = -1
# book.price = 1
# print(book._price)
#
# Book.run()
# book.run()
# Book.say()
# book.say()

 


五、继承&多态

# 继承&多态
class A:
    pass


class B:
    pass


class C(A):
    pass


class D(C):
    pass


# class D(A,B):
#     pass

#查看继承关系
print(D.__bases__)
# 查看D继承的全部父类关系
print(D.__mro__)

print("================================")
# 属性及方法继承
class Father:
    money = 100

    def hello(self):
        print("hello world")


class Son(Father):
    pass


s = Son()
print(s.money)
s.hello()


print("================================")

class Father:
    money = 100

    def hello(self):

        print("hello world")


class Mother:
    money = 200

    def cook(self):
        print("煮饭")


class Son(Father, Mother): #就近原则
    pass


s = Son()
print(s.money)
s.hello()
s.cook()


print("================================")
# 多态
class Animal(object):
    def play(self):
        pass


class Tiger(Animal):
    def play(self):
        print("正在表演老虎吃人")


class Lion(Animal):
    def play(self):
        print("正在表演狮子跳火圈")


class Person(object):
    def show(self, a: Animal):
        print("动物开始表演了")
        a.play()


p = Person()
tiger = Tiger()
lion = Lion()
# 让老虎表演
p.show(tiger)
# 让狮子表演
p.show(lion)

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值