我正在阅读http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#587的 Java 代码约定。
其中,他们提到我们应该避免使用对象来访问类变量或方法,而应该使用类名。
避免使用对象访问类(静态)变量或方法。请改用类名。例如:
Run Code Online (Sandbox Code Playgroud)classMethod(); //OK AClass.classMethod(); //OK anObject.classMethod(); //AVOID!
在术语、性能或其他方面是否有特殊原因?
[更新]:完整代码
我总是对 pyhton 的静态方法感到困惑,但根据这个(最后一个答案),它应该可以工作!
得到错误:
AttributeError: 类 MyConnection 没有属性“myuser”
class MyConnection:
def __init__(self, hostname, port, user, password):
myhostname = hostname
myport = port
myuser = user
mypassword = password
isisessid = None
@staticmethod
def connect():
my_session = MyConnection()
headers = {'content-type': 'application/json'}
headers['Authorization'] = 'Basic ' + string.strip(
base64.encodestring(MyConnection.myuser + ':' + MyConnection.mypassword))
body = json.dumps({'username': MyConnection.myuser, 'password': MyConnection.mypassword,
'services': ['platform', 'namespace']})
uri = '/session/1/session'
connection = httplib.HTTPSConnection(MyConnection.myhostname, MyConnection.myport)
connection.connect()
try:
connection.request('POST', uri, body, headers)
response = connection.getresponse() …Run Code Online (Sandbox Code Playgroud) 我有一个静态方法来执行 find() 并在应用程序启动时将营销活动数据添加到 Redis。
CampaignSchema.statics.activeCampaignsToRedis = function () {
this
.find()
.where('active').equals(true)
...
};
Run Code Online (Sandbox Code Playgroud)
我想添加一个保存后挂钩,每当添加或修改新的营销活动时,该挂钩都会重新运行静态方法来更新 Redis 中的数据。
CampaignSchema.post('save', function (next) {
// call CampaignSchema.statics.activeCampaignsToRedis();
});
Run Code Online (Sandbox Code Playgroud) 卡在我作业的一个特定部分:在循环外有一个 return 语句。如果您查看代码,您可以猜测我在这里要做什么。程序的其余部分有效,但此方法不断给我相同的错误语句:“缺少返回语句”。
private static String HighOrLow (int[] numbers)
{
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i] > average) {
return (numbers[i] + "is above the average");
}
else if (numbers[i] < average) {
return (numbers[i] + " is below the average");
}
else {
return (numbers[i] + " is equal to the average");
}
}
Run Code Online (Sandbox Code Playgroud)
我意识到有些东西应该在 forloop 之外,但不知道如何去做。任何有用的帮助表示赞赏。
16 年 4 月 5 日:首先,感谢大家的帮助!我已经准备好并准备好了......除了每个数字,高或低,都在高于平均水平。Paul Guiheen 有正确的想法,我很感激,但我必须为每个数组整数打印单独的行。
我有以下代码:
struct CommonVariables
{/*some common variables that need to be proceed*/};
struct CommonHandler
{
static void foo(const CommonVariables& vars) {/*processed vars*/}
void bar(const CommonVariables& vars) {/*processed vars*/}
};
struct AnotherVariables
{/*another variables*/};
struct AnotherHandler
{
static void foo(const AnotherVariables& vars) {/*processed vars*/}
void bar(const AnotherVariables& vars) {/*processed vars*/}
};
struct Derived : CommonHandler, AnotherHandler
{};
Run Code Online (Sandbox Code Playgroud)
当我尝试调用 Derived::foo(/ any variable type /) 或 Derived d; d.bar(/ any variable type /),编译器给我一个错误:“对'foo(or bar)'的引用不明确”。
然而在下面我有几乎相同的情况:
struct DifferentHandler
{
static void foo(const CommonVariables& vars) {} …Run Code Online (Sandbox Code Playgroud) 我有下面的代码,我想修改静态函数中类的变量,但有一些错误。\n我如何用“this”指针修复它?
\n\n类中的静态成员无法访问“this”指针,另一方面,我试图访问静态成员函数中的类变量,因此我正在寻找一种使用类“this”指针的方法我”来做到这一点。
\n\nclass me {\n public:\n void X() { x = 1;}\n void Y() { y = 2;}\n\nstatic void Z() {\n x = 5 ; y = 10;\n}\n\npublic:\n int x, y;\n};\n\nint main() {\n me M;\n\n M.X();\n M.Y();\n M.Z();\n\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我懂了error:
\n\n在静态成员函数中无效使用成员 \xe2\x80\x98me::x\xe2\x80\x99。
\n
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.Main(args);//instance reference error,use type name instead
var p = new Program();
Program.Main(args);//error disappears
}
}
Run Code Online (Sandbox Code Playgroud)
我想我明白静态与对象实例无关,但我遇到的问题是类不是对象的同义词吗?或者不是在创建对象时使用类?那么,如果类本质上是对象,为什么当我使用类名时错误会消失?
我知道我还没有创建一个实例,以后Main也不会。这是唯一不同的东西吗?也许在我正在上的这门课中没有正确解释它。
我对python很陌生,无法理解python中的静态方法是什么(例如__new__())以及它有什么作用。谁能解释一下?太感谢了
我需要一个模块内的命名空间,用于许多不同的静态方法做类似的工作。从我的研究中我了解到,在 Python 编程中,拥有一个充满静态方法的类被认为是反模式:
class StatisticsBundle:
@staticmethod
def do_statistics1(params):
pass
@staticmethod
def do_statistics2(params):
pass
Run Code Online (Sandbox Code Playgroud)
如果这不是一个好的解决方案,那么最好的做法是允许我getattr(SomeNameSpace, func_name)在同一个模块中进行命名空间查找吗?
这是基类:
class Product
{
public:
static void RegisterClass() {
string b = __FUNCTION__;
};
}
Run Code Online (Sandbox Code Playgroud)
这是派生类。
class Milk: Product
{}
Run Code Online (Sandbox Code Playgroud)
在主函数中我这样调用静态方法:
main(){
Milk.RegisterClass();
}
Run Code Online (Sandbox Code Playgroud)
然后写入值Product::RegisterClass变量b。Milk::RegisterClass有没有办法在静态方法中获取值。
我不想实例化这些类。这个场景背后的主要目标是在某处注册Milk字符串。
static-methods ×10
c++ ×3
python ×3
class ×2
inheritance ×2
java ×2
c# ×1
if-statement ×1
method-call ×1
mongoose ×1
node.js ×1
oop ×1
reflection ×1
return ×1