산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python OOP:예제가 있는 클래스, 객체, 상속 및 생성자

Python의 OOP

Python의 OOP 다른 일반 프로그래밍 언어와 동일하게 객체와 클래스를 사용하는 데 중점을 둔 프로그래밍 접근 방식입니다. 개체는 모든 실제 엔터티가 될 수 있습니다. Python을 사용하면 개발자가 코드 재사용성에 중점을 둔 OOP 접근 방식을 사용하여 애플리케이션을 개발할 수 있습니다. Python에서 클래스와 객체를 만드는 것은 매우 쉽습니다.

수업이란 무엇입니까?

Python의 클래스는 데이터와 함수의 논리적 그룹입니다. 임의의 콘텐츠를 포함하고 따라서 쉽게 액세스할 수 있는 데이터 구조를 자유롭게 생성할 수 있습니다.

예를 들어 온라인으로 고객 세부 정보를 가져오려는 은행 직원의 경우 customer class로 이동합니다. , 거래 세부 정보, 출금 및 예금 세부 정보, 미결제 부채 등과 같은 모든 속성이 나열됩니다.

이 자습서에서는 다음을 배우게 됩니다.

파이썬 클래스를 정의하는 방법

클래스를 정의하려면 다음 사항을 고려해야 합니다.

1단계) Python에서 클래스는 "클래스" 로 정의됩니다. 키워드

class myClass():

2단계) 클래스 내에서 이 클래스의 일부인 함수 또는 메서드를 정의할 수 있습니다.

def method1 (self):
   print "Guru99"
def method2 (self,someString): 
   print "Software Testing:" + someString

3단계) 함수, 루프, if 문 등의 코드와 마찬가지로 클래스의 모든 항목은 들여쓰기됩니다. 들여쓰기되지 않은 모든 항목은 클래스에 없습니다.

참고 :Python에서 "self" 사용에 대해

4단계) 클래스의 개체를 만들려면

c = myClass()

5단계) 클래스에서 메소드를 호출하려면

c.method1()
    c.method2(" Testing is fun")

6단계) 전체 코드는 다음과 같습니다.

# Example file for working with classes
class myClass():
  def method1(self):
      print("Guru99")
        
  def method2(self,someString):    
      print("Software Testing:" + someString)
  
      
def main():           
  # exercise the class methods
  c = myClass ()
  c.method1()
  c.method2(" Testing is fun")
  
if __name__== "__main__":
  main()

상속 작동 방식

상속은 객체 지향 프로그래밍에서 사용되는 기능입니다. 기존 클래스를 거의 또는 전혀 수정하지 않고 새 클래스를 정의하는 것을 말합니다. 새 클래스를 파생 클래스라고 합니다. 그리고 상속되는 것을 기본이라고 합니다. . Python은 상속을 지원합니다. 다중 상속도 지원합니다. . 클래스는 하위 클래스 또는 상속 클래스라는 다른 클래스에서 속성 및 동작 메서드를 상속할 수 있습니다.

Python 상속 구문

class DerivedClass(BaseClass):
    body_of_derived_class

1단계) 다음 코드 실행

# Example file for working with classes
class myClass():
  def method1(self):
      print("Guru99")
        
  
class childClass(myClass):
  #def method1(self):
        #myClass.method1(self);
        #print ("childClass Method1")
        
  def method2(self):
        print("childClass method2")     
         
def main():           
  # exercise the class methods
  c2 = childClass()
  c2.method1()
  #c2.method2()

if __name__== "__main__":
  main()

childClass에서 method1은 정의되지 않았지만 부모 myClass에서 파생되었습니다. 출력은 "Guru99"입니다.

2단계) 라인 # 8 및 10의 주석 처리를 제거합니다. 코드를 실행합니다.

이제, 메소드 1이 childClass에 정의되고 출력 "childClass Method1"이 올바르게 표시됩니다.

3단계) 9번 줄의 주석 처리를 제거합니다. 코드 실행

구문을 사용하여 부모 클래스의 메서드를 호출할 수 있습니다.
ParentClassName.MethodName(self)

우리의 경우 myClass.method1(self)를 호출하고 Guru99가 예상대로 인쇄됩니다.

4단계 ) 19행의 주석을 제거합니다. 코드를 실행합니다.

자식 클래스의 메소드 2가 호출되고 예상대로 "childClass method2"가 출력됩니다.

파이썬 생성자

생성자는 객체를 미리 정의된 값으로 인스턴스화하는 클래스 함수입니다.

이중 밑줄(_)로 시작합니다. 그것은 __init__() 메소드

아래 예에서는 생성자를 사용하여 사용자의 이름을 사용하고 있습니다.

class User:
    name = ""

    def __init__(self, name):
        self.name = name

    def sayHello(self):
        print("Welcome to Guru99, " + self.name)

User1 = User("Alex")
User1.sayHello()

출력은 다음과 같습니다.

Guru99에 오신 것을 환영합니다, Alex

Python 2 예제

위의 코드는 Python 3 예제이며, Python 2에서 실행하려면 다음 코드를 고려하십시오.

# How to define Python classes
# Example file for working with classes
class myClass():
  def method1(self):
      print "Guru99"
        
  def method2(self,someString):    
      print "Software Testing:" + someString
      
   
      
def main():           
  # exercise the class methods
  c = myClass ()
  c.method1()
  c.method2(" Testing is fun")
  
if __name__== "__main__":
  main()


#How Inheritance works
# Example file for working with classes
class myClass():
  def method1(self):
      print "Guru99"
        
      
class childClass(myClass):
  #def method1(self):
        #myClass.method1(self);
        #print "childClass Method1" 
        
  def method2(self):
        print "childClass method2"     
         
def main():           
  # exercise the class methods
  c2 = childClass()
  c2.method1()
  #c2.method2()

if __name__== "__main__":
  main()

요약:

"클래스"는 기능과 데이터의 논리적 그룹입니다. Python 클래스는 객체 지향 프로그래밍의 모든 표준 기능을 제공합니다.


python

  1. C# 클래스 및 개체
  2. 파이썬 객체 지향 프로그래밍
  3. 파이썬 상속
  4. Raspberry Pi 및 Python으로 로봇 구축
  5. 구조체와 클래스의 차이점:C++ 예제로 설명
  6. EXAMPLE이 있는 Python String strip() 함수
  7. 예제가 있는 컬렉션의 Python 카운터
  8. 예제가 있는 Python의 type() 및 isinstance()
  9. 예제가 있는 Python 목록 index()
  10. 자바 - 객체와 클래스