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

파이썬 - 객체 지향

이전 페이지다음 페이지

파이썬은 처음부터 객체 지향 언어였습니다. 이 때문에 클래스와 객체를 만들고 사용하는 것은 정말 쉽습니다. 이 장은 Python의 객체 지향 프로그래밍 지원 사용에 대한 전문가가 되는 데 도움이 됩니다.

객체 지향(OO) 프로그래밍에 대한 이전 경험이 없는 경우 기본 개념을 이해할 수 있도록 이에 대한 입문 과정이나 최소한 일종의 자습서를 참조할 수 있습니다.

그러나 여기에 속도를 높여주는 객체 지향 프로그래밍(OOP)에 대한 간략한 소개가 있습니다.

OOP 용어 개요

수업 만들기

클래스 문은 새 클래스 정의를 만듭니다. 클래스 이름은 class 키워드 바로 다음에 옵니다. 다음과 같이 콜론이 옵니다 -

class ClassName:
   'Optional class documentation string'
   class_suite

예시

다음은 간단한 Python 클래스의 예입니다. -

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

인스턴스 개체 생성

클래스의 인스턴스를 생성하려면 클래스 이름을 사용하여 클래스를 호출하고 __init__ 인수를 전달합니다. 방법이 허용됩니다.

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

속성 액세스

객체와 함께 점 연산자를 사용하여 객체의 속성에 액세스합니다. 클래스 변수는 다음과 같이 클래스 이름을 사용하여 액세스됩니다. -

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

이제 모든 개념을 통합하여 -

라이브 데모
#!/usr/bin/python

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

위의 코드가 실행되면 다음 결과가 생성됩니다 -

Name :  Zara ,Salary:  2000
Name :  Manni ,Salary:  5000
Total Employee 2

언제든지 클래스 및 개체의 속성을 추가, 제거 또는 수정할 수 있습니다. −

emp1.age = 7  # Add an 'age' attribute.
emp1.age = 8  # Modify 'age' attribute.
del emp1.age  # Delete 'age' attribute.

속성에 액세스하기 위해 일반 명령문을 사용하는 대신 다음 기능을 사용할 수 있습니다. -

hasattr(emp1, 'age')    # Returns true if 'age' attribute exists
getattr(emp1, 'age')    # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age')    # Delete attribute 'age'

내장 클래스 속성

모든 Python 클래스는 내장 속성을 계속 따르며 다른 속성과 마찬가지로 점 연산자를 사용하여 액세스할 수 있습니다. −

위 클래스의 경우 이러한 모든 속성에 액세스하려고 합니다.

라이브 데모
#!/usr/bin/python

class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__
print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

위의 코드가 실행되면 다음 결과가 생성됩니다 -

Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2, 
'displayEmployee': <function displayEmployee at 0xb7c8441c>, 
'__doc__': 'Common base class for all employees', 
'__init__': <function __init__ at 0xb7c846bc>}

객체 파괴(가비지 수집)

Python은 불필요한 객체(내장 유형 또는 클래스 인스턴스)를 자동으로 삭제하여 메모리 공간을 확보합니다. Python이 더 이상 사용하지 않는 메모리 블록을 주기적으로 회수하는 프로세스를 가비지 컬렉션이라고 합니다.

Python의 가비지 수집기는 프로그램 실행 중에 실행되며 개체의 참조 횟수가 0에 도달하면 트리거됩니다. 개체의 참조 횟수는 개체를 가리키는 별칭 수가 변경됨에 따라 변경됩니다.

객체의 참조 횟수는 새 이름이 할당되거나 컨테이너(목록, 튜플 또는 사전)에 배치될 때 증가합니다. del을 사용하여 삭제하면 개체의 참조 횟수가 감소합니다. , 참조가 재할당되거나 참조가 범위를 벗어납니다. 개체의 참조 횟수가 0에 도달하면 Python이 자동으로 수집합니다.

a = 40      # Create object <40>
b = a       # Increase ref. count  of <40> 
c = [b]     # Increase ref. count  of <40> 

del a       # Decrease ref. count  of <40>
b = 100     # Decrease ref. count  of <40> 
c[0] = -1   # Decrease ref. count  of <40> 

일반적으로 가비지 수집기가 분리된 인스턴스를 파괴하고 해당 공간을 회수할 때 이를 눈치채지 못할 것입니다. 그러나 클래스는 특별한 메소드 __del__()를 구현할 수 있습니다. 인스턴스가 파괴되려고 할 때 호출되는 소멸자라고 합니다. 이 방법은 인스턴스에서 사용하는 비메모리 리소스를 정리하는 데 사용할 수 있습니다.

예시

이 __del__() 소멸자는 곧 파괴될 인스턴스의 클래스 이름을 출력합니다 -

라이브 데모
#!/usr/bin/python

class Point:
   def __init__( self, x=0, y=0):
      self.x = x
      self.y = y
   def __del__(self):
      class_name = self.__class__.__name__
      print class_name, "destroyed"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3

위의 코드를 실행하면 다음과 같은 결과가 나온다 -

3083401324 3083401324 3083401324
Point destroyed

참고 − 이상적으로는 별도의 파일에 클래스를 정의한 다음 가져오기를 사용하여 기본 프로그램 파일로 가져와야 합니다. 성명서.

클래스 상속

처음부터 시작하는 대신 새 클래스 이름 뒤의 괄호 안에 상위 클래스를 나열하여 기존 클래스에서 파생하여 클래스를 만들 수 있습니다.

자식 클래스는 부모 클래스의 속성을 상속하며 해당 속성을 자식 클래스에 정의된 것처럼 사용할 수 있습니다. 자식 클래스는 부모의 데이터 멤버와 메서드를 재정의할 수도 있습니다.

구문

파생 클래스는 부모 클래스와 매우 유사하게 선언됩니다. 그러나 상속받을 기본 클래스의 목록은 클래스 이름 뒤에 주어집니다 -

class SubClassName (ParentClass1[, ParentClass2, ...]):
   'Optional class documentation string'
   class_suite

예시

라이브 데모
#!/usr/bin/python

class Parent:        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent method'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"

   def childMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
c.setAttr(200)       # again call parent's method
c.getAttr()          # again call parent's method

위의 코드가 실행되면 다음 결과가 생성됩니다 -

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

비슷한 방법으로 다음과 같이 여러 상위 클래스에서 클래스를 구동할 수 있습니다. -

class A:        # define your class A
.....

class B:         # define your class B
.....

class C(A, B):   # subclass of A and B
.....

issubclass() 또는 isinstance() 함수를 사용하여 두 클래스와 인스턴스의 관계를 확인할 수 있습니다.

방법 재정의

항상 부모 클래스 메서드를 재정의할 수 있습니다. 부모의 메서드를 재정의하는 한 가지 이유는 하위 클래스에서 특별하거나 다른 기능을 원할 수 있기 때문입니다.

예시

라이브 데모
#!/usr/bin/python

class Parent:        # define parent class
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent): # define child class
   def myMethod(self):
      print 'Calling child method'

c = Child()          # instance of child
c.myMethod()         # child calls overridden method

위의 코드가 실행되면 다음 결과가 생성됩니다 -

Calling child method

기본 과부하 방법

다음 표에는 자신의 클래스에서 재정의할 수 있는 몇 가지 일반 기능이 나열되어 있습니다.

시니어 번호 방법, 설명 및 샘플 호출
1

__init__ ( self [,args...] )

생성자(선택적 인수 포함)

샘플 호출:obj =className(args)

2

__del__( 자기 )

소멸자, 개체 삭제

샘플 호출 :del obj

3

__repr__( 자기 )

평가 가능한 문자열 표현

샘플 호출 :repr(obj)

4

__str__( 자기 )

인쇄 가능한 문자열 표현

샘플 호출 :str(obj)

5

__cmp__ ( 자기, x )

개체 비교

샘플 호출 :cmp(obj, x)

연산자 오버로딩

2차원 벡터를 나타내기 위해 Vector 클래스를 생성했다고 가정하고 더하기 연산자를 사용하여 추가하면 어떻게 됩니까? 대부분의 경우 파이썬이 당신에게 소리칠 것입니다.

그러나 __add__를 정의할 수 있습니다. 클래스에서 메서드를 사용하여 벡터 추가를 수행하면 더하기 연산자가 예상대로 작동합니다 -

예시

라이브 데모
#!/usr/bin/python

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)
   
   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2

위의 코드가 실행되면 다음 결과가 생성됩니다 -

Vector(7,8)

데이터 은닉

객체의 속성은 클래스 정의 외부에서 표시되거나 표시되지 않을 수 있습니다. 이중 밑줄 접두사로 속성의 이름을 지정해야 하며 이러한 속성은 외부인에게 직접 표시되지 않습니다.

예시

라이브 데모
#!/usr/bin/python

class JustCounter:
   __secretCount = 0
  
   def count(self):
      self.__secretCount += 1
      print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount

위의 코드가 실행되면 다음 결과가 생성됩니다 -

1
2
Traceback (most recent call last):
   File "test.py", line 12, in <module>
      print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'

Python은 클래스 이름을 포함하도록 이름을 내부적으로 변경하여 해당 구성원을 보호합니다. object._className__attrName과 같은 속성에 액세스할 수 있습니다. . 마지막 줄을 다음과 같이 바꾸면 효과가 있습니다 -

.........................
print counter._JustCounter__secretCount

위의 코드가 실행되면 다음 결과가 생성됩니다 -

1
2
2

python

  1. C# 클래스 및 개체
  2. 파이썬 데이터 유형
  3. 파이썬 연산자
  4. 파이썬 통과 문
  5. 파이썬 사전
  6. Python 사용자 정의 예외
  7. 파이썬 객체 지향 프로그래밍
  8. 파이썬 상속
  9. 자바 싱글톤 클래스
  10. 자동 비전 개체 추적