- 它允许用户使用自己的属性创建对象。
- 方法充当使用某些参数和对象本身或仅对对象本身返回某些值或更改对象的函数。 ###创建类的通用格式
class NameOfClass: #use camel casing to write the class name.
def __init__(self, x, y):
self.x=x
self.y=y
def some_method(self):
pass
为什么要使用OOPS?
- 它使项目的开发和管理更加可管理。
- 数据隐藏的功能。
- 代码的可重复使用
糟糕的概念
- 班级
- 对象
- 封装
- 抽象
- 多态性
- 继承
- 构造函数
- Destructor
班级
- 类是用于创建对象的蓝图。
- 它创建一个具有相同属性和方法的对象。
class NameOfClass: #use camel casing to write the class name.
def __init__(self, x, y):
self.x=x
self.y=y
def some_method(self):
pass
目的
- 这是一个具有预定义属性和方法的实体。
class Dog:
def __init__(self, name):
self.name=name
def bark(self):
print(f'{self.name} woof')
newdog=Dog('tom')
newdog.bark()
#output- It will print 'tom woof'
- 使用类狗创建的所有对象该对象将具有属性名称和一个名为bark()的方法。
构造函数
- 这将使用类创建对象。
- init 用于创建对象。
class Dog:
def __init__(self, name):
self.name=name
newdog=Dog('tom') # New object is constructed with attribute name tom.
驱动器
- 它用于删除对象。
class Dog:
def __init__(self, name):
self.name=name
newdog=Dog('tom') # New object is constructed with attribute name tom.
del newdog # the object new dog will be deleted.
封装
- 封装使我们可以从外部访问中隐藏对象的属性和方法。
- 需要保护的属性和方法从单个下划线开始:_
- 需要私有的属性和方法从双重下划线开始:__
class Person:
def __init__(self, name, age):
self.__name = name # private attribute
self._age = age # protected attribute
def get(self): # This method is used to get the name that is private.
return self.__name
def set(self, name): # This method will take some input names and change the value of the attribute.
self.__name = name
def get_age(self): # This method is used to get the age that is protected.
return self._age
def set_age(self, age): # This method will take some input age and change the value of the attribute.
self._age = age
def __show(self): # private method
return f"My name is {self.__name} and I am {self._age} years old."
def _speak(self): # protected method
return f"My name is {self.__name}"
a=Person('Name',5)
print(a._Person__name) # accesing private variable it gives output Name
print(a._age) # acessing private variable it gives output age
a._Person__name='New Name' # change the private variable without using any method.
print(a.get_name()) # it return the name of object
遗产
- 继承使我们能够基于另一个类(父类或base类)创建一个新类(子类或派生类)。
- 子类继承父级的所有属性和方法。
- 此外,儿童类是自己的独特属性和方法。
- 有几种类型的继承:
- 单个继承:仅使用一个类得出子类。
- 多重继承:使用多个类得出子类。
- 多级继承:在这个孩子中,班级是从另一个父班的子类继承的
- 层次结构继承:使用单亲类创建多个子类。
- 混合继承:多种类型的继承发生
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(f'My name is {self.name}, and I am {self.age} years old.')
class NewPerson(Person): # inheriting parent class in child class
def speak(self): # accessing parent class attribute.
print("I am new person")
class AnotherPerson(Person): # inheriting parent class in child class
def __init__(self, name, age, sport):
super().__init__(name, age) # accessing parent class attribute in child class using super and changing the
self.sport = sport # child class attribute
def speak(self):
print(f'My favorite sport is {self.sport}.')
D = AnotherPerson("Bruno", 9, 'Football')
C = NewPerson("Missa", 6)
D.show() # accessing parent class method in child class
#output- My name is Bruno, and I am 9 years old.
D.speak() # child class accessing its own attributes
#output- My favorite sport is Football.
C.show() # accessing parent class method in child class
#output- My name is Missa, and I am 6 years old.
C.speak() # child class accessing its own attributes
#output- I am new Person
抽象
- 抽象使我们可以隐藏用户不需要的类和方法。
- 可以通过将任何类的父类别设置为ABC之后的ABC(抽象类基础)。
- 如果您需要创建一个抽象方法,也从ABC模块导入AbstrackMethod。
- 之后,我们可以使用@AbstractMethod Decorator创建一个抽象方法。
from abc import ABC, abstractmethod
class Person(ABC): # create an abstract class
@abstractmethod # create an abstract method
def speak(self):
pass
def show(self):
print("I am a Person.")
class AnotherPerson(Person):
def speak(self):
print("I am another person")
bruno = AnotherPerson()
bruno.speak() # ignoring abstract method of abstract class
#output- I am another person
bruno.show() # non-abstract method of the abstract class still works
#output- I am a Person
person= Person() #this will throw an error abstract class can't be instantiated.
多态性
- 它只是指不同类可以具有相同的方法名称,并且也代表方法覆盖。
- 可以通过两种方式实现python中的多态性:方法覆盖和鸭子型。
A.方法过度骑行
方法覆盖允许儿童类具有对父类中已经定义的方法的不同定义。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print(f'My name is {self.name} and I am {self.age} years old.')
class NewPerson(Person):
pass
class AnotherPerson(Person):
def speak(self): # over-riding method of parent's class
print(f'Hello! My name is {self.name} and I am {self.age} years old.')
nemo = Person("Nemo", 2)
bruno = AnotherPerson("Bruno", 9)
nemo.speak() # parent's class method runs
#output- My name is Nemo and I am 2 years old.
bruno.speak() # child's class method runs
#output- Hello! My name is Bruno and I am 9 years old.
B.鸭打字
Duck Typing允许不同类型的类具有具有自己定义的相同方法名称。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self): # method of first class
print(f'My name is {self.name} and I am {self.age} years old.')
class AnotherPerson:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self): # method of second class with same name
print(f'Hello! My name is {self.name} and I am {self.age} years old')
nemo =Person("Nemo", 2)
bruno = Another("Bruno", 9)
nemo.speak() # method of first-class runs
# output- My name is Nemo and I am 2 years old.
bruno.speak() # method of the second class with the same name runs
#output- Hello! My name is Bruno and I am 9 years old.
Dunder/魔术方法:
- dunder或魔术方法是Python类中使用的特殊方法。
- 它们用于定义类的对象,以防万一它们与内置的Python操作一起使用。
- 一些常用的义工方法是 init ,(self,...), str (self), len (self),等。
- dunder方法无法调用,当通过构建的python函数调用时,它们会自动运行。
class Book:
def __init__(self,title,author,page):
self.title=title
self.author=author
self.page=page
def __str__(self):
return f'This {self.title} wrote by {self.author}'
def __len__(self):
return self.page
kid_book=Book('New Book', 'Myself', 15)
print(kid_book)
#output- This Newbook wrote by Myself
print(len(kid_book))
#output- 15
参考
- 极客的怪胎。 “继承python的类型”。取自https://www.geeksforgeeks.org/types-of-inheritance-python/
- 极客的怪胎。 “在python班级中”。取自https://www.geeksforgeeks.org/self-in-python-class
- 极客的怪胎。 “ Python中的多态性”。取自https://www.geeksforgeeks.org/polymorphism-in-python/?ref=gcse
- 极客的怪胎。 “ python中的Dunder或Magic Method”。取自https://www.geeksforgeeks.org/dunder-magic-methods-python/