파이썬 객체와 클래스 Python Object and Classes
파이썬은 객체-지향 언어입니다.
파이썬에서, 모든 것은 객체인데, 즉, int , str , bool even modules, functions도 또한 객체입니다.
객체 지향 프로그래밍은 프로그램을 만들기 위하여 객체들을 사용하며, 이들 객체는 데이터와 동작을 저장합니다.
Python is an object-oriented language. In python everything is object i.e int , str , bool even modules, functions are also objects.
Object oriented programming use objects to create programs, and these objects stores data and behaviors.
클래스 정의하기 Defining class
파이썬에서 클래스 이름의 앞에는 키워드 class가 오며 그 뒤에는 콜론(:)이 옵니다.
클래스에는 일반적으로 데이터와 동작을 정의하는 메소드를 저장하는 데이터 필드가 포함되어 있습니다.
또한 파이썬의 모든 클래스에는 초기화자 (또한 일반적으로 생성자라고도 함)라는 특별한 메소드가 포함되어 있는데, 이 초기화자는 새 객체를 만들 때마다 자동으로 invoke 됩니다.
예제를 보자.
Class name in python is preceded with class keyword followed by colon ( : ). Classes commonly contains data field to store the data and methods for defining behaviors. Also every class in python contains a special method called initializer (also commonly known as constructors), which get invoked automatically every time new object is created.
Let’s see an example.
here we have created a class called Person which contains one data field called name and method whoami().
What is self ??
All methods in python including some special methods like initializer have first parameter self . This parameter refers to the object which invokes the method. When you create new object the self parameter in the __init__ method is automatically set to reference the object you have just created.
Creating object from class
Expected Output:
Note: When you call a method you don’t need to pass anything to self parameter, python automatically does that for you behind the scenes.
You can also change the name data field.
Expected Output:
Although it is a bad practice to give access to your data fields outside the class. We will discuss how to prevent this next.
Hiding data fields
To hide data fields you need to define private data fields. In python you can create private data field using two leading underscores. You can also define a private method using two leading underscores.
Let’s see an example
Expected Output:
Let’s try to access __balance data field outside of class.
Expected Output:
As you can see now __balance is not accessible outside the class.
In next chapter we will learn about operator overloading.
'Python 배우기' 카테고리의 다른 글
변수_타입 variable_type.py (0) | 2016.03.06 |
---|---|
변수_정의 variable_definition.py (0) | 2016.03.06 |
Running phython programs (0) | 2016.03.05 |
Applications for Python 파이썬 적용 (0) | 2016.03.05 |
PyQt5 Beginner tutorial (0) | 2016.03.04 |