OOPS의 중추 (python)
21047 단어 oopprogrammingpython
The scope of this article is to help you understand the concepts of oops quickly and not an in-depth tutorial on coding with oops.
대상을 대상으로 하는 프로그래밍 시스템은 OOPS라고도 부르며 프로그래밍 면접의 핫이슈 중의 하나이다.인터뷰에서 나는 여러 차례 이 개념에 관한 문제(직접과 간접 문제)를 물었지만, 사실 나는 대부분의 시간을 이 문제들에 대답할 수 없었다. 왜냐하면 나는 지금까지 그것에 대해 명확한 이해를 한 적이 없기 때문이다.그러나 내가 그 장점을 자세히 관찰하고 내가 가장 좋아하는 프로그래밍 언어로 이해하려고 할 때, 나는 코드를 작성할 때 개선판이라고 생각했다. 나는 그것이 당신의 기능과 지식을 향상시키는 데 도움을 줄 수 있기를 바란다.
OOPS를 이해하도록 하겠습니다.
기둥이 네 개 있다
봉인
encapsulation (the action of enclosing something in or as if in a capsule.)
지금 만약 당신이 이 단어의 뜻을 이해한다면, 당신은 그것을 당신의 코드와 연결시켜서, 우리에게 이 예를 보여 줄 수 있습니다.
class Cat:
def __init__(self):
self.sound = "meow"
def speak(self):
print("Cat says: {}".format(self.sound))
c = Cat()
c.speak()
# change the price
c.sound = "bow-wow"
c.speak()
#OUTPUT
Cat says: meow
Cat says: bow-wow
위의 예에서 클래스cat에는 변수 sound가 있습니다. 이것은 구조 함수의 기본값으로 설정되어 있습니다. 이 변수의 값, 즉 c.sound = "bow-wow"
을 변경할 것입니다. 이제 봉인의 의미를 알았습니다. 위의 정의에 따라 클래스를 캡슐로 봅시다. 이 코드는 봉인을 따른다고 생각합니까?사실은 그렇지 않다.이러한 상황을 피하기 위해서, 우리는 사유 변수를 설명할 수 있습니다. Python에서, 우리는 밑줄을 접두사로 삼아 사유 속성, 즉 single u나double를 표시합니다.
class Cat:
def __init__(self):
self.__sound = "meow"
def speak(self):
print("Cat says: {}".format(self.__sound))
c = Cat()
c.speak()
# change the price
c.sound = "bow-wow"
c.speak()
#OUTPUT
Cat says: meow
Cat says: meow
현재, 그것은 이미 봉인되었다.이게 봉인입니다.따라서 이 분야의 일부 실제 예는 다음과 같다.
상속권
Inherit (to receive a quality, characteristic, etc. from your parents or family.)
위에서 정의한 바와 같이, 이것은 우리가 다른 클래스로부터 계승하는 방법과 속성을 정의할 수 있도록 한다.만약 당신이 새로운 종류를 필요로 한다면, 수정이 매우 적거나 수정이 없다면, 당신은 이 개념을 응용하세요.
기류를 부류라고 하고 파생류를 자류라고 한다.뻔하다.
예를 하나 보도록 하겠습니다.
class Family:
def __init__(self, family_name, number_of_members, country):
self.family_name = family_name
self.number_of_members = number_of_members
self.country=country
def member_says(self):
print(f"Hey, I am from {self.family_name} family and there are {self.number_of_members} members in family")
class Family_detailed:
def __init__(self, family_name, number_of_members, country):
self.family_name = family_name
self.number_of_members = number_of_members
self.country=country
def member_says(self):
print(f"Hey, I am from {self.family_name} family and there are {self.number_of_members} members in family")
def which_country(self):
print(f"The {self.family_name} family has roots from {self.country}" )
a = Family("Rodrigues",5,"Peru")
b = Family_detailed("Bezos",15,"United States of America")
a.member_says()
b.member_says()
b.which_country()
#Output
Hey, I am from the Rodrigues family and there are 5 members in the family
Hey, I am from the Bezos family and there are 15 members in the family
The Bezos family has roots in the United States of America
첫 번째 클래스의 목적은 성과 구성원 수를 표시하는 것이지만 두 번째 클래스는 국가와 같은 정보를 표시하기를 원한다.보시다시피, 여기는 흔히 볼 수 있는 코드가 많습니다. 계승을 사용해서 간소화합시다.class Family:
def __init__(self, family_name, number_of_members, country):
self.family_name = family_name
self.number_of_members = number_of_members
self.country=country
def member_says(self):
print(f"Hey, I am from {self.family_name} family and there are {self.number_of_members} members in family")
class Family_detailed(Family):
def which_country(self):
print(f"The {self.family_name} family has roots from {self.country}" )
a = Family("Rodrigues",5,"Peru")
b = Family_detailed("Bezos",15,"United States of America")
a.member_says()
b.member_says()
b.which_country()
#Output
Hey, I am from the Rodrigues family and there are 5 members in the family
Hey, I am from the Bezos family and there are 15 members in the family
The Bezos family has roots in the United States of America
와, 보시다시피 코드가 현저히 줄어들었어요.그래서 이것이 유산이다. 다음 지주로 넘어가자.추상
추상화(특정 대상, 사람 또는 상황과 관련된 개념이 아니라)
그것을 더욱 잘 이해하기 위해서, 우리는 자동차 한 대를 예로 들면, 사람들은 자동차를 수천 수만 개의 단독 부품으로 보지 않고, 그것을 정의가 명확하고 행위가 독특한 물체로 본다.그들은 이 부분의 복잡성과 어떻게 서로 협력하는지 이해할 필요가 없다.자판기도 마찬가지다. 돈을 넣고 가장 좋아하는 간식만 얻고 싶을 뿐, 이 시스템이 어떻게 작동하는지 알 필요는 없다.
간단하게 말하자면 추상적인 중점은 사용자의 숨겨진 절차나 방법의 내부 실현에 있다.이런 방식을 통해 사용자는 그들이 무엇을 하고 있는지 알지만, 일을 어떻게 완성했는지 모른다.
이것은 다른 지주와 약간 다르다.Python은 기본적으로 추상 클래스를 부여하지 않습니다.반면 파이톤은 ABC라는 추상 기류(ABC) 기반에 적합한 모듈을 달았다.키워드 @abstractmethod를 사용하면 방법이 추상적으로 변합니다
우리 간단한 예를 하나 들자.
from abc import ABC, abstractmethod
class Company(ABC):
def work(self):
pass
class Manager(Company):
def work(self):
print("I assign work to and manage team")
class Employee(Company):
def work(self):
print("I complete the work assigned to me")
# Driver code
R = Manager()
R.work()
K = Employee()
K.work()
다태성
다태성(몇 가지 다른 형식으로 나타난 상황)
Ben 10이 좋은 예입니다.그는 한 사람이지만, 그는 다양한 형식으로 세계를 위해 봉사할 수 있다.
프로그래밍으로 돌아가는 것은 서로 다른 장면의 유형을 표시하기 위해 방법/조작부호를 사용하는 것을 가리킨다.
Python은 다중 모드를 사용하여 같은 방식으로 여러 클래스를 사용할 수 있습니다.이 목적을 달성하기 위해서, 우리는 하나의 순환을 만들고, 한 그룹의 대상을 순환할 수 있다.이것은 대상이 가리키는 클래스를 보지 않고 방법을 호출할 수 있도록 합니다.
class Class1():
def pt(self):
print("This function determines class 1")
class Class2():
def pt(self):
print("This function determines class 2.")
obj1 = Class1()
obj2 = Class2()
for type in (obj1, obj2): # creating a loop to iterate through the obj1, obj2
type.pt()
#Output
This function determines class 1
This function determines class 2.
마찬가지로 조작부호에 관해서는 +
조작부호를 살펴보자.> print(1+2)
3
> print ("a"+"b")
> ab
보시다시피 +
연산자는 서로 다른 데이터 형식에 대해 서로 다른 행위 방식을 가지고 있습니다.여러분, 이 글은 여기까지입니다.
잊지 마라❤ 혹은📑 만약 네가 이 문장을 좋아한다면.
좋은 하루 되세요.
즐거운 코딩!
Reference
이 문제에 관하여(OOPS의 중추 (python)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/kedark/pillars-of-oops-in-python-k6a텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)