python类getter和setters静态方法和类方法

时间:2014-08-01 02:58:18

标签: python class

class Spam(object): 
#a_string = 'candy'
def __init__(self, sold=0, cost=0): 
    self.sold = sold
    self.cost = cost
@staticmethod
def total_cost():
    return True

@classmethod
def items_sold(cls, how_many):

@property
def silly_walk(self):
    return print (self.a_string)

@silly_walk.setter
def silly_walk(self, new_string):
    self.a_string = new_string.upper()

def do_cost(self):
    if self.total_cost():
        print('Total cost is:', self.cost)

  from spam import Spam

def main ():
    cost = 25
    sold = 100
    a_string = 'sweets'
    sp = Spam(100, 25)
    sp.do_cost()
    sw = Spam.silly_walk(a_string)
    sw.silly_walk()

if __name__ == '__main__':
    main()

所以我是python的新手,我不明白如何使用setter和getter。所以我想做的是:

使用@property为名为silly_walk的属性创建一个setter和getter。将setter大写字母设为silly_walk字符串。 显示将访问静态方法的示例代码。 显示将使用silly_walk setter和getter的示例代码。

我很害怕" self"在课堂上,我不确定我做的是否正确

更新: 问题是@classmethod没有返回和缩进错误,所以一切都是固定的,谢谢大家

1 个答案:

答案 0 :(得分:0)

self是惯例。由于你在一个类中,你没有函数,你有方法。方法期望引用调用它们的对象作为第一个参数,按照约定命名为self。你可以随意调用它。

class Foo(object):
    def __init__(itsa_me_maaaario, name):
        itsa_me_maaario.name = "Mario"

同样有效。

至于你的其余代码 - 那你的问题是什么?看起来你的二传手有点奇怪,但除此之外它应该工作大多没事。这样更好:

class Spam(object): # inherit from object in py2 for new-style classes
    def __init__(self, a_string, sold=0, cost=0) # put the positional arg first
        ...
    @staticmethod
    def total_cost():
        # you have to do something meaningful here. A static method can't access
        # any of the objects attributes, it's really only included for grouping
        # related functions to their classes.
    @classmethod
    def items_sold(cls, how_many):
        # the first argument to a classmethod is the class, not the object, so
        # by convention name it cls. Again this should be something relevant to
        # the class not to the object.
    @property
    def silly_walk(self):
        return self.a_string
        # don't call itself.
    @silly_walk.setter
    def silly_walk(self, new_string):
        self.a_string = new_string
        # it really just hides the attribute.

例如,我有一个我为了抽象我负责的计算机系统而构建的课程。它可能是这样的:

class System(object):
    type_ = "Base system"
    def __init__(self, sitenum, devicenum, IP):
        self._sitenum = sitenum
        self._devicenum = devicenum
        self._IP = IP
        # the leading underscores are a flag to future coders that these are
        # "private" variables. Nothing stopping someone from using it anyway,
        # because System()._IP is still that attribute, but it makes it clear
        # that they're not supposed to be used that way.
    @staticmethod
    def ping_system(IP):
        subprocess.call(["ping",IP], shell=True) # OH GOD SECURITY FLAW HERE
        # group this with Systems because maybe that's how I want it? It's an
        # aesthetic choice. Note that this pings ANY system and requires an
        # argument of an IP address!
    @classmethod
    def type_of_system(cls):
        return cls.type_
        # imagine I had a bunch of objects that inherited from System, each w/
        # a different type_, but they all inherit this....
    @property
    def description(self):
        return "Site {}, Device {} @ {}".format(self._sitenum,
                                                self._devicenum,
                                                self._IP)
    @description.setter
    def description(self, *args):
        if len(args) == 3:
            self._sitenum, self._devicenum, self._IP = args
        elif len(args) == 1 and len(args[0]) == 3:
            self._sitenum, self._devicenum, self._IP = args[0]
        else:
            raise ValueError("Redefine description as Sitenum, Devicenum, IP")

示例:

computer = System(1, 1, '192.168.100.101')
System.ping_system('192.160.100.101') # works
computer.type_of_system # "Base system"
computer.description # "Site 1, Device 1 @ 192.168.100.101"
new_description = [1, 2, '192.168.100.102']
computer.description = new_description
# invokes description.setter
computer._devicenum # is 2 after the setter does its magic.