-
Chapter 2. Object-Oriented Programming - 2카테고리 없음 2017. 7. 15. 22:36
2.3 Class Definitions
- A class serves as the primary means for abstraction in object-oriented programming.
- In Python, every piece of data is represented as an instance of some class.
- 이름 정리: member functions(=methods) // attributes(=fields, instance variables, or datamembers)
2.3.1 Example: CreditCard Class
-
[The self Identifier]
In Python, the self identifier plays a key role.
Syntactically, self identifies the instance upon which a method is invoked.
객체가 'self' parameter를 가지는 이유: The interpreter automatically binds the instance upon which the method is invoked to the self parameter.
[The constructor]
A user can create an instance of the Credit Card class using a syntax as:
cc = CreditCard('John Doe', '1st Bank', '5391 0375 9387 5309', 1000)
---> Internally, this results in a call to the special named __init__ method that serves as the constructor of the class. Its primary responsibility is to establish the state of a newly created credit card object with appropriate instance variables.
[Encapsulation]
**복습: a single leading underscore in the name of a data member, such as _balance, implies that it is intended as nonpublic. Users of a class should not directly access such members.
As a general rule, we will treat all data members as nonpublic. This allows us to better enforce a consistent state for all instances. We can provide accessors, such as get_balance, to provide a user of our class read-only access to a trait.
[ErrorChecking]
- 인자에 대한 타입 검사를 실시하는가? 만약 타입 검사를 하지 않을 경우, 프로그램에서 crash가 발생할 수 있다.
- if __name__ == '__main__': python namespace에 대한 이해가 필요함.
.....
2.3.2 Operator Overloading and Python's Special Methods
- python은 operator overloading을 지원한다. '+' operator의 경우, 피연산자가 str일 때는 concatenation으로, int일때는 plus로 사용되는데, 이는 operator overloading의 결과다. 클래스 내에 __add__라는 method를 정의하면 '+'에 대한 overloading이 가능하다.
- __add__ , __sub__, __mul__, __floordiv__, __mod__, __iadd__ __isub__, __pos__ 등이 있다.