回到原始状态。我试图将我的思维方式从纯脚本转换为OOP。我有一个可以正常工作的python例程,但是我想对它进行OOP操作。我被困在想在班级之间通过/返回的位置。
所以我将数据库连接视为对象。
我还有另一个对象Pointcloud,它有一个子类/子类Surface(Pointcloud)。
Surface需要连接到数据库,选择一些记录,然后关闭连接。这存储在Connect类中(尽管仍然不确定如何使cur.close()起作用)。
一旦我弄清楚了这一点,我将很顺利地进入OOP(我希望)。一旦我有了正确的思维方式,生活就会轻松很多。因此,请您浏览一下我的代码并解释/给出一个示例,以了解它应该是什么? Connect,Pointcloud和Surface对象分别工作。
import dbconfig
import psycopg2
class Connect:
def __init__(self, schema):
self.schema = schema
@staticmethod
def get_connection():
conn = psycopg2.connect(host=dbconfig.DATABASE_CONFIG['host'],
user=dbconfig.DATABASE_CONFIG['user'],
password=dbconfig.DATABASE_CONFIG['password'],
dbname=dbconfig.DATABASE_CONFIG['dbname'])
print('connection made')
return conn
# add error catching
@staticmethod
def close_connection():
# implement cur.close()
# print('connection closed')
pass
class Pointcloud:
def __init__(self, photobatch):
self.photobatch = photobatch
def list_pointclouds(self):
return '{}'.format(self.photobatch)
class Surface(Pointcloud):
def __init__(self, photobatch, surface_type):
super().__init__(photobatch)
self.surface_type = surface_type
# this inherits all the Pointcloud attributes
# so each surface is a type of pointcloud
# we add the surface type so we can distinguish between top and base surfaces
# which is an attribute of this instance
def import_pointcloud(self):
# connect to database
print('connecting')
Connect.get_connection()
# do some database stuff to import the pointcloud and construct a numpy array
Connect.close_connection()
# return the resulting numpy array
class Bounding(Pointcloud):
# a different subclass of pointcloud
pass