面向对象探析(一)

概览

在面向对象编程中,编写表示现实中的事物和情景的类,并基于这些类来创建对象;编写类时,定义的一大类对象都有通用的行为。基于类创建对象时,每个对象都自动具备这种通用行为,然后可根据需求赋予每个对象独特的个性.

Python是一门特别彻底的面向对象编程的语言,在其他语言中,有些数据类型不属于对象类型。

面向对象和面向过程的区别

  • 面向过程:解决问题时,关注的是解决的每一个过程
  • 面向对象:解决问题时,关注的是解决问题的所需要的对象

相关函数

class Person: # 定义一个类
    pass

p=Person() # 实例化对象
p.name="Mike" #  增加属性

查看实例化对象的所有属性

print(p.__dict__)
# 返回结果:{'name': 'Mike'}

查看实例化对象所属的类

print(p.__class__)
# 返回结果:<class '__main__.Person'>

类操作

创建类、初始化类属性

class Friend:  # 创建一个朋友类
    def __init__(self, name, age, gender):  # 初始化类属性
        self.name = name
        self.age = age
        self.gender = gender
        self.default=0  # 给属性指定默认值

定义类方法

    def introduce(self):
        print("My name is ", self.name)

    def my_age(self):
        print("My age is ", self.age)

    def my_gender(self):
        print("I'm a ", self.gender)

初始化类

if __name__ == '__main__':
    f = Friend("Mike", 20, "boy")  # 初始化类
    f.introduce()	# 调用类方法
# 返回结果:My name is  Mike

限定类属性

class Parents:
    __slots__ = ["name"]  # 限定类属性的创建
    pass


if __name__ == '__main__':
    parents = Parents()
    parents.name = "Mike"
    parents.age = 1 # 无法创建列表外的新属性

# 返回结果:AttributeError: 'Parents' object has no attribute 'age'

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

class Method:
    def instance_method(self):  # 方法传递的是实例本身[实例方法]
        print("This is a instance method.")

    @classmethod
    def class_method(cls):  # 方法传递的是类[类方法]
        print("This is a class method.")

    @staticmethod
    def static_method():  # 静态方法不需传递参数[静态方法]
        print("This is a static method.")


if __name__ == '__main__':
    method = Method() 	 # 实例化对象
    method.instance_method() # 调用实例方法
    Method.class_method()	# 调用类方法
    Method.static_method()	# 调用静态方法
    
'''
返回值:
This is a instance method.
This is a class method.
This is a static method.

在Python中,实例方法类方法和静态方法都是存储在Method类中,通过调用__dict__查看
	print(Method.__dict__)
返回值:
{'__module__': '__main__', 'instance_method': <function Method.instance_method at 0x000002557EE52790>, 'class_method': <classmethod object at 0x000002557ED85D30>, 'static_method': <staticmethod object at 0x000002557EDF4190>, '__dict__': <attribute '__dict__' of 'Method' objects>, '__weakref__': <attribute '__weakref__' of 'Method' objects>, '__doc__': None}
'''

方法

实例方法

class Method:
    def instance_method(self):
        print("This is a instance method.")
        print(self)


method = Method()
method.instance_method()
# 返回值:
# This is a instance method.
# <__main__.Method object at 0x000001C1246F5D30>

类方法

class Method:
    @classmethod
    def class_method(cls):
        print("This is a class method.")
        print(cls)


Method.class_method()
# 返回值:
# This is a class method.
# <class '__main__.Method'>

通过查看库函数

查看库函数

可见,类方法也可用通过实例进行调用,但是会自动忽略实例对象

class Method:
    @classmethod
    def class_method(cls):
        print("This is a class method.")
        print(cls)


method = Method()
method.class_method()
# 返回值:
# This is a class method.
# <class '__main__.Method'>

使用派生类调用类方法

class Method:
    @classmethod
    def class_method(cls):
        print("This is a class method")
        print(cls)


class New_Method(Method):  # 则基类为Method,派生类为New_Method
    pass


new_method = New_Method()
new_method.class_method()
# 返回值:
# This is a class method
# <class '__main__.New_Method'> 可见,如果使用派生类调用类方法,则派生类对象作为隐含的第一个参数传递

静态方法

class Method:
    @staticmethod
    def static_method():
        print("This is a static method.")


Method.static_method()
# 返回值:This is a static method.

在这里插入图片描述

继承

编写类时,并非总要从空白开始。如果你要编写的类是另一个类的增加版,可使用继承。一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法

class Parents: # 父类
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sleep(self):
        print(self.name + " sleeping.")

    def play(self):
        print(self.name + " playing.")


class Child(Parents):  # 继承父类Parents[子类]
    def __init__(self, name, age):
        super().__init__(name, age)  # super() 调用父类里面的初始化方法 [构造方法]
        
        
if __name__ == '__main__':
    child = Child("Jack", 20)
    child.sleep()  # 可以调用使用父类的方法
# 返回值:Jack sleeping.

如果在子类中不添加 __ init __

class Parents:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def sleep(self):
        print(self.name + " sleeping.")

    def play(self):
        print(self.name + " playing.")


class Child(Parents): # 继承父类会默认调用父类的构造方法
    pass # 不添加占位符会报错


if __name__ == '__main__':
    child = Child("Jack", 20)
    child.sleep()
# 返回值:Jack sleeping.

重写方法

class Parents:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fruit(self):
        print(self.name, "like apple.")


class Child(Parents):
    def __init__(self, name, age, gender):
        super().__init__(name, age)
        self.gender = gender

    def fruit(self):  # 重写父类方法
        print(self.name, "like pear.")


if __name__ == '__main__':
    child = Child("Mike", 20, "man")
    child.fruit() # 在调用方法时,会优先使用子类中的同名方法

将示例用作属性

编辑代码时,给类添加的细节越来越多,属性和方法清单以及文件都越来越长。在这种情况下,可能需要将类的一部分作为一个独立的类提取出来,可以将大型类分成多个协同工作的小类

class Parents:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print(self.name, "eat.")


class Child:
    def __init__(self, gender, name, age):
        self.gender = gender
        self.parent = Parents(name, age)

    def eat(self):
        self.parent.eat() # 将类的示例作为属性


if __name__ == '__main__':
    child = Child("man", "Mike", 20)
    child.eat()
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Meaauf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值