[pyhon] Object Oriented Programming(2)
Class design
Here, let's design our own class and defined object methods.
First example (2D point class)
import math
class Point(object):
def __init__(self, x, y):
"""Construct a point object based on (x, y) coordinates.
Parameters:
x (float): x coordinate in a 2D cartesian grid. y (float): y coordinate in a 2D cartesian grid.
"""
self._x = x
self._y = y
def x_cord(self):
"""
returns current x position of an object
"""
return self.x
def y_cord(self):
"""
returns current y position of an object
"""
return self.y
def move(self, dx, dy):
"""
moves current position to new given x, y coordinate position
Parameters:
dx(int): new x coordinate
dy(int): new y coordinate
"""
self.x += dx
self.y += dy
Class definition starts with keyword class, followed by class name and (object):Basic definition syntax
class Classname(object):
"""comment"""
def method_1(self, [args]):
method_1 body
def method_2(self, [args]):
method_2 body
def method_3(self, [args]):
method_3 body
Creates a class called classname
to represent the ADT specified. The methods of the class are , method_1
, method_2
and so on.Using object method
p = Point(2, -3)
p.x_cord()
>> 2
p. y_cord()
>> -3
--------------------------------------
p.move(1, 2)
p.x_cord()
>> 3
p.y_cord()
>> -1
Reference
この問題について([pyhon] Object Oriented Programming(2)), 我々は、より多くの情報をここで見つけました https://velog.io/@heesungj7/pyhon-Object-Oriented-Programming2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol