Joh*_*ohu 2 python oop inheritance class-method static-functions
我知道C++和Java,我不熟悉Pythonic编程.所以也许这是我想要做的坏风格.
考虑下面的例子:
class foo:
def a():
__class__.b() # gives: this is foo
bar.b() # gives: this is bar
foo.b() # gives: this is foo
# b() I'd like to get "this is bar" automatically
def b():
print("this is foo")
class bar( foo ):
def b( ):
print("this is bar")
bar.a()
Run Code Online (Sandbox Code Playgroud)
请注意,我没有使用self
参数,因为我没有尝试创建类的实例,因为不需要我的任务.我只是试图以一种可以覆盖函数的方式引用函数.
你想要的是a
成为一种类方法.
class Foo(object):
@classmethod
def a(cls):
Foo.b() # gives: this is foo
Bar.b() # gives: this is bar
cls.b() # gives: this is bar
@staticmethod
def b():
print("this is foo")
class Bar(Foo):
@staticmethod
def b():
print("this is bar")
Bar.a()
Run Code Online (Sandbox Code Playgroud)
我编辑了你的风格以匹配Python编码风格.使用4个空格作为缩进.不要在括号之间加上额外的空格.大写和CamelCase类名.
A staticmethod
是类上的方法,它不接受任何参数,也不对类的属性起作用.A classmethod
是类的一种方法,它将类自动作为属性获取.
你继承的使用很好.