一个只允许我填充创建的第一个类型的实例的类

发布于 2024-12-02 13:26:52 字数 1541 浏览 0 评论 0原文

它的作用是这样的:类的第一个实例(在本例中为 mok1 )的内容充满了水。我可以无限地填充它,但是一旦创建第一个实例,我就只能填充该实例并由任何其他实例生成错误。有没有更干净、更好的方法来做到这一点?现在我使用类的 var 和实例的 var 之间的差异,这会让人们感到困惑,因为它们是不同的变量。谢谢大家;)

class mok:
    _content = 'EMPTY'
    def __init__( self flavour ):
        self.flavour = flavour

    def fill( self ):
        if mok._content == 'EMPTY':
            self._content = '1'
            mok._content = 1

        if self._content == '1':    
            print 'Filling mok!'
        else:
            print 'Error: This is a different mok!'

mok1 = mok( 'thea' )    
mok2 = mok( 'coffee' )

mok1.fill()
mok1.fill()
mok2.fill()
mok1.fill()

输出:

Filling mok!

Filling mok!

Error: This is a different mok!

Filling mok!

我找到了解决方案:

class mok:
    _mok_with_water = 0

    def __init__( self, color, flavour ):
        self.color = color
        self.flavour = flavour

    def printcolor( self ):
        print 'Mok color =', self.color
    print 'Mok flavour =', self.flavour

    def fill( self ):
    self.printcolor()
        if mok._mok_with_water == 0:
        mok._mok_with_water = self

    if mok._mok_with_water == self:
        print 'Filling mok!'
    else:
        print 'Error: This is a different mok!'

    def empty( self ):
        if self == mok._mok_with_water:
            mok._mok_with_water = 0

mok1 = mok( 'geel', 'thee' )    
mok2 = mok( 'zwart', 'koffie' )

mok1.fill()
mok1.fill()
mok2.fill()
obj = mok1.empty()
obj = mok2.fill()
obj = mok1.fill()

This is what it does: The content of the first instance of the class ( in this case mok1 ) gets filled with water. I can fill it infinitely but as soon as the first instance is created, I can only fill that instance and generate a error by any other instance. Is there a cleaner and better way to do this? Now I use the difference in the class's var and the instance's var which is confusing for people because it are different variables. Thnx guys;)

class mok:
    _content = 'EMPTY'
    def __init__( self flavour ):
        self.flavour = flavour

    def fill( self ):
        if mok._content == 'EMPTY':
            self._content = '1'
            mok._content = 1

        if self._content == '1':    
            print 'Filling mok!'
        else:
            print 'Error: This is a different mok!'

mok1 = mok( 'thea' )    
mok2 = mok( 'coffee' )

mok1.fill()
mok1.fill()
mok2.fill()
mok1.fill()

output:

Filling mok!

Filling mok!

Error: This is a different mok!

Filling mok!

I've found the solution:

class mok:
    _mok_with_water = 0

    def __init__( self, color, flavour ):
        self.color = color
        self.flavour = flavour

    def printcolor( self ):
        print 'Mok color =', self.color
    print 'Mok flavour =', self.flavour

    def fill( self ):
    self.printcolor()
        if mok._mok_with_water == 0:
        mok._mok_with_water = self

    if mok._mok_with_water == self:
        print 'Filling mok!'
    else:
        print 'Error: This is a different mok!'

    def empty( self ):
        if self == mok._mok_with_water:
            mok._mok_with_water = 0

mok1 = mok( 'geel', 'thee' )    
mok2 = mok( 'zwart', 'koffie' )

mok1.fill()
mok1.fill()
mok2.fill()
obj = mok1.empty()
obj = mok2.fill()
obj = mok1.fill()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

许仙没带伞 2024-12-09 13:26:52

我认为这个问题与如何有效地实现单例有关。虽然您显然希望允许多个实例(因此您没有单例),但您仍然需要识别第一个实例。

您的解决方案的问题在于您没有识别第一个实例,而是识别您调用 Fill() 的第一个实例。

您需要在构造函数中设置类变量。也许这篇优秀的维基百科文章提供了一些额外的想法。

I think the question is related to that of how to effectively implement a Singleton. While you apparently want to allow multiple instances (hence you don't have a Singleton), you still need to identify that first instance.

The problem with your solution is that you are not identifying the first instance, but the first instance on which you called Fill().

You need to set your class variable in the constructor. Maybe this excellent Wikipedia article provides some additional ideas.

早茶月光 2024-12-09 13:26:52

你为什么这么做?尝试:

class mok():

    def __init__(self, flavour):

        self.flavour = flavour
        self.is_empty = True

    def fill(self):

        print 'Filling mok!'
        self.is_empty = False


mok1 = mok('coffe')
mok2 = mok('tea')

mok1.fill()
mok1.fill()
mok2.fill()
mok1.fill()

输出:

Filling mok!
Filling mok!
Filling mok!
Filling mok!

我很困惑......

Why are you doing it? Try:

class mok():

    def __init__(self, flavour):

        self.flavour = flavour
        self.is_empty = True

    def fill(self):

        print 'Filling mok!'
        self.is_empty = False


mok1 = mok('coffe')
mok2 = mok('tea')

mok1.fill()
mok1.fill()
mok2.fill()
mok1.fill()

Output:

Filling mok!
Filling mok!
Filling mok!
Filling mok!

I'm confused...

幸福%小乖 2024-12-09 13:26:52

那么您想要一个只允许您填充创建的第一个类型的实例的类吗?

class ContentError(Exception):
    pass

class Mok(object):

    _content = None

    def __init__(self, flavour):
        self.flavour = flavour
        if Mok._content is None:
            Mok._content = flavour

    def fill(self):
        if self._content == self.flavour:
            print 'Filling!'
        else:
            raise ContentError('This is a different mok!')

So you want a class that only allows you to fill instances of the first type created?

class ContentError(Exception):
    pass

class Mok(object):

    _content = None

    def __init__(self, flavour):
        self.flavour = flavour
        if Mok._content is None:
            Mok._content = flavour

    def fill(self):
        if self._content == self.flavour:
            print 'Filling!'
        else:
            raise ContentError('This is a different mok!')
清风疏影 2024-12-09 13:26:52

从 Java 的角度来看,这可以通过工厂模式来解决。

你有 2 个类 Mok,它不能被填充,而 FillableMok 继承了 Mok(因此是一个 Mok),它可以被填充。工厂只生产一个 FillableMok (本质上是一个单例),所有其他都是默认的、不可填充的 Mok。

class Mok(Object):
    def fill(self):
        raise CannotBeFilledException()

class FillabelMok(Mok):
    def fill(self):
        filled = True # or whatever

class Factory(Object):
    _fillableMok = None

    def createMok(self):
        if _fillableMok:
           return Mok()
        _fillableMok = FillableMok()
        return _fillableMok()

这在语法上可能不正确,因为我已经有一段时间没有使用 Python 了。但希望这个想法是明确的。欢迎改进。

From a Java perspective this could be solved by a Factory pattern.

You'd have 2 classes Mok, which can't be filled, and FillableMok which inherits Mok (and thus is-a Mok) which can be filled. The factory only ever produces a single FillableMok (essentially a singleton), all the others are default, non-fillable Moks.

class Mok(Object):
    def fill(self):
        raise CannotBeFilledException()

class FillabelMok(Mok):
    def fill(self):
        filled = True # or whatever

class Factory(Object):
    _fillableMok = None

    def createMok(self):
        if _fillableMok:
           return Mok()
        _fillableMok = FillableMok()
        return _fillableMok()

This may not be syntactically correct as it has been a while since I used Python. But the idea is hopefully clear. Improvements welcome.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文