Python面向对象
- 面向对象基本语法
class Student(object):
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
def run(self):
print(f'{self.name}正在跑步')
def eat(self):
print(f'{self.name}正在吃东西')
s1 = Student('小明', 18, 1.75)
s2 = Student('小美', 19, 1.65)
s1.run()
s1.eat()
s2.eat()
- self语句的使用
class Student(object):
__slots__ = ('name', 'age')
def __init__(self, x, y):
self.name = x
self.age = y
def sayHello(self):
print('大家好,我是', self.name)
s1 = Student('张三', 18)
print('s1 的名字是', s1.name)
s1.sayHello()
s1.city = '上海'
s1.name = '刘明'
print(s1.name)
__init__ 魔法方法
import datetime
n = datetime.datetime(2021, 4, 13, 8, 40, 54, 900)
print(n)
print(repr(n))
class Person(object):
def __init__(self, name, age):
print('__init__方法被调用了')
self.name = name
self.age = age
def __del__(self):
print('__del__方法被调用了')
def __repr__(self):
return 'hello'
def __str__(self):
return '{} {}'.format(self.name, self.age)
def __call__(self, *args, **kwargs):
print("args = {}, kwargs = {}".format(args, kwargs))
fn = kwargs['fn']
return fn(args[0], args[1])
p = Person('zhangsan', 18)
print(p)
m = p(1, 2, fn=lambda x, y: x + y)
__eq__ 方法的使用功能
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
p1 = Person('zhangsan', 18)
p2 = Person('zhangsan', 18)
print('0x%X' % id(p1))
print('0x%X' % id(p2))
print(p1 == p2)
nums1 = [1, 2, 3]
nums2 = [1, 2, 3]
- 面向对象练习
"""
房子(House)有户型、总面积、剩余面积 和 家具名称列表 属性
新房子没有任何的家具
将 家具的名称 追加到 家具名称列表 中
判断 家具的面积 是否 超过剩余面积,如果超过,提示不能添加这件家具
家具(Furniture) 有 名字 和 占地面积 属性,其中
席梦思(bed) 占地 4 平米
衣柜(chest) 占地 2 平米
餐桌(table) 占地 1.5 平米
将以上三件 家具 添加 到 房子 中
打印房子时,要求输出:户型、总面积、剩余面积、家具名称列表
"""
class House(object):
def __init__(self, house_type, total_area, fur_list=None):
if fur_list is None:
fur_list = []
self.house_type = house_type
self.total_area = total_area
self.fur_list = fur_list
self.free_area = total_area * 0.6
def add_fur(self, fur):
if fur.area < self.free_area:
self.fur_list.append(fur.name)
self.free_area -= fur.area
else:
print(f'房子剩余空间不够了,不能添加 "{fur.name}" 这个家具了')
def __str__(self):
return '户型:{},总面积:{} 平米,剩余面积:{:.2f} 平米,家具名称列表:{}'.format(self.house_type, self.total_area,
self.free_area, self.fur_list)
class Furniture(object):
def __init__(self, name, area):
self.name = name
self.area = area
if __name__ == '__main__':
house = House('三室一厅', 116)
bed = Furniture('席梦思', 4)
chest = Furniture('衣柜', 2)
table = Furniture('餐桌', 1.5)
plane = Furniture('飞机', 100)
house.add_fur(bed)
house.add_fur(chest)
house.add_fur(table)
house.add_fur(plane)
print(house)
- 魔法方法介绍
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(self.name + '正在吃东西')
def __eq__(self, other):
return self.name == other.name and self.age == other.age
p1 = Person('小明', 18)
p2 = Person('小李', 20)
print(str(p1))
- 内置属性
class Person(object):
"""
这是一个人类
"""
__slots__ = ('name', 'age')
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print(self.name + '正在吃东西')
p1 = Person('zhangsan', 18)
print(p1.__doc__)
print(Person.__doc__)
print(p1.__module__)
- 把对象当做一个字典使用
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getitem__(self, item):
return self.__dict__[item]
p1 = Person('张三', 18)
p1['name'] = 'lisi'
print(p1.name)
print(p1['name'])
- 对象属性和类属性
class Person(object):
type = '人类'
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person('张三', 18)
p2 = Person('李四', 20)
p1.type = 'human'
Person.type = '哺乳类'
print(Person.type)
print(p2.type)
print(p1.type)
- 私有属性的使用
import datetime
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.__money = 1000
def test(self):
self.__money += 10
def get_money(self):
print('查询余额时间 {}'.format(datetime.datetime.now()))
return self.__money
def set_money(self, new_money):
if type(new_money) == int:
print('修改余额了')
self.__money = new_money
else:
print('修改余额失败')
def __demo(self):
print('我是demo函数')
def test_demo(self):
self.__demo()
p1 = Person('张三', 18)
print(p1.name, p1.age)
p1._Person__demo()
print(p1.get_money())
p1.set_money(2000)
print(p1.get_money())
- 类方法和静态方法
class Person(object):
type = '人类'
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self, food):
print(self.name + '正在吃' + food)
@staticmethod
def demo():
print('我是demo方法,我被调用了')
@classmethod
def test(cls):
print('test函数使用了类属性: {}'.format(cls.type))
class Calculator(object):
@staticmethod
def add(a, b):
return a + b
@staticmethod
def minus(a, b):
return a - b
print(Calculator.add(1, 2))
p1 = Person('张三', 18)
p2 = Person('李斯', 20)
p1.eat('樱桃')
p1.demo()
Person.eat(p2, '西红柿鸡蛋面')
Person.demo()
p1.test()
Person.test()
- 单例设计模式
class Singleton(object):
__instance = None
__isfirst = True
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
def __init__(self, a, b):
if self.__isfirst:
self.a = a
self.b = b
self.__isfirst = False
s1 = Singleton('abc', '好的')
s2 = Singleton('hello', '世界')
print(s1.a, s1.b)
print(s1 is s2)
class Person(object):
__count = 0
def __init__(self, name, age):
Person.__count += 1
self.name = name
self.age = age
@classmethod
def get_count(cls):
return cls.__count
p1 = Person('张三', 18)
p2 = Person('李斯', 20)
p3 = Person('王武', 21)
p4 = object.__new__(Person)
p4.__init__('刘明', 22)
print(p1, p2, p3, p4)
print(Person.get_count())
- 面向对象三大特性
def test():
a = 23
a += 3
print('hello')
print('good')
class Persion(object):
type = '人类'
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print('吃东西')
- 继承的使用
class Animal(object):
def __init__(self, name, age):
self.name = name
self.age = age
def sleep(self):
print(self.name + '正在睡觉')
class Dog(Animal):
def bark(self):
print(self.name + '正在汪汪叫……')
class Student(Animal):
def study(self):
print(self.name + '正在好好学习')
d1 = Dog('大黄', 6)
d1.sleep()
d1.bark()
s1 = Student('小明', 18)
s1.sleep()
s1.study()
- python里继承的特点
class A(object):
def demo_a(self):
print('我是A类里的方法demo_a')
def foo(self):
print('我是A类里的方法foo')
class B(object):
def demo_b(self):
print('我是B类里的方法demo_b')
def foo(self):
print('我是B类里的方法foo')
class C(A, B):
pass
c = C()
c.demo_a()
c.demo_b()
c.foo()
print(C.__mro__)
- python里的多继承
class A(object):
pass
class B(object):
def foo(self):
print('我是B类里的foo方法')
class C(A):
def foo(self):
print('我是C类里的foo方法')
class D(B):
pass
class X(D, C):
pass
x = X()
x.foo()
print(X.__mro__)
- 私有属性的继承特点
class Animal(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.__weight = 50
def eat(self):
print(self.name + '正在吃东西')
def __test(self):
print('我是Animal类里的test方法')
class Dog(Animal):
def __demo(self):
print('我是Dog里的私有的demo方法')
d = Dog('小六', 3)
print(d.name)
d.eat()
print(d._Animal__weight)
- 新式类和经典类
class Animal(object):
pass
class Dog:
pass
|