douzizang7783 2010-11-30 13:47
浏览 40
已采纳

对象中的PHP和Python静态方法,两个不同的世界......?

i'm php coder, trying to get into python world, and it's very hard for me.

Biggest enjoy of static methods in php is automatic builder of instance. No need to declare object, if you needed it once, in every file (or with different constructor params , in one line)

<?php
class Foo { 
    function __constructor__(){
        $this->var = 'blah';
    }
   public static function aStaticMethod() {
       return $this->var;
   }
}

echo Foo::aStaticMethod();
?>

we can call constructor from static method don't we? and we can access everything in class as it would be simple method ... we can even have STATIC CONSTRUCTOR in php class and call it like so: Object::construct()->myMethod(); (to pass different params every time)

but not in python???? @staticmethod makes method in class a simple function that doesn't see totally anything ??

class socket(object):

def __init__(self):
    self.oclass = otherclass()
    print 'test' # does this constructor called at all when calling static method??                

@staticmethod
def ping():
    return self.oclass.send('PING') # i can't access anything!!!


print Anidb.ping()

I can't access anything from that god damned static method, it's like a standalone function or something like this..??

Maybe I'm using the wrong decorator? Maybe there's something like php offers with static methods in python?

1) Please tell why static methods is isolated 2) Please tell me how to make the same behavior like php static methods have. 3) Please tell me alternative practical use of this, if php static methods behavior is a bad thing

P.s. the goal of all this to write totally less code as much as possible. P.p.s Heavy commenting of sample code is appreciated

Thank you.

  • 写回答

3条回答 默认 最新

  • doucuo8618 2010-11-30 14:20
    关注

    I see you've already accepted another answer, but I'm not sure that it will work with your code. Specifically, the oclass variable is only created for instances of the class, not for the class itself. You could do it like this:

    class socket(object):
        oclass = otherclass()                
    
        @classmethod
        def ping(cls):
            return cls.oclass.send('PING')
    
    socket.ping()
    

    However, using your existing code and removing all decorators, you could simply instantiate it and use a method on the same line:

    socket().ping()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题