理解Python类

thr*_*434 0 python class

我想学习python类,但我不明白.为什么这个简单的例子不返回"6"?它返回了<function TEST.f at 0x00000000029ED378>.我也尝试了,TEST.f()但他告诉我,这个论点self不见了.self不仅应该存在于类中,而python会自动填充它吗?

#! coding=utf-8

class TEST:
    def __init__(self):
        self.x = 6
    def f(self):
        return(self.x)

print(TEST.f)
Run Code Online (Sandbox Code Playgroud)

ayc*_*dee 11

您需要创建该类的实例.

test = TEST()
print test.x()
Run Code Online (Sandbox Code Playgroud)

但是你还需要调用方法和变量不同的东西.

class TEST:
    def __init__(self):
        self._x = 6
    def x(self):
        return(self._x)
Run Code Online (Sandbox Code Playgroud)

否则你正在重新定义的价值x.