我们如何在一个文件中定义一个类,并在Python中的其他文件中实现它?我知道在C/C++中,我们可以使用头(.h(文件来实现这一点。
例如。。
#### Time .h
#ifndef TIME_H
#define TIME_H
class Time
{
private :
int hour;
int minute;
int second;
public :
//with default value
Time(const int h = 0, const int m = 0, const int s = 0);
// setter function
void setTime(const int h, const int m, const int s);
// Print a description of object in " hh:mm:ss"
void print() const;
//compare two time object
bool equals(const Time&);
};
#endif
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;
Time :: Time(const int h, const int m, const int s)
: hour(h), minute (m), second(s)
{}
void Time :: setTime(const int h, const int m, const int s)
{
hour = h;
minute = m;
second = s;
}
void Time :: print() const
{
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << "n";
}
bool Time :: equals(const Time &otherTime)
{
if(hour == otherTime.hour
&& minute == otherTime.minute
&& second == otherTime.second)
return true;
else
return false;
}
我想知道这样的东西是否可以在Python中实现?此外,我正在努力想出一个设计,使之成为可能。我将感谢在这方面的任何帮助。它不是强制性的,有相同的语法如下所述,我准备做不同的模型。只是定义应该与实现分开。因此,客户端代码可以直接导入所需的类或方法。
# species.py
Class Human:
def __init__(self, a, b c, d):
“””
This initialises the Human class…..
“””
def __dothis__(self, g, h, i):
“””
Random documentation
“””
def __getage__(self):
“””
Random documentation
“””
# species_impl.py
def Human__init__(a, *args):
print(“Arguments…”)
print(a)
for i in args:
print(i)
def Human__dothis__(self, g, h, i):
print(g, h, i)
def Human__getage__(self):
print(“hello this is your age”)
您只需让每个方法调用相应的函数就可以做到这一点。
类定义文件可以导入实现文件。然后,定义的实现名称将仅对定义文件可见,而对方法的调用方不可见。
from species_impl import *
class Human:
def __init__(self, a, b c, d):
"""
This initialises the Human class…..
"""
Human__init__(self, a, b, c, d)
def __dothis__(self, g, h, i):
"""
Random documentation
"""
return Human__dothis__(self, g, h, i)
def __getage__(self):
"""
Random documentation
"""
return Human__getage__(self)
顺便说一句,你可能不应该自己制定扣篮方法,这些方法应该只用于内置方法。