3

我在下面有一个基本的简单示例来展示我正在尝试做的事情。

这是我正在使用但无法更改的文件(它是一个已安装的库):

treats = 5

class Pet(object):
    def eat(self):
        # Uses the variable 'treats' in this method

这是我正在处理的文件:

from other_file import Pet

class Dog(Pet):
    # Change the value of 'treats' here

我正在尝试更改该方法treats的子类中的变量eat(),而不必覆盖该方法。

当谈到 python 中的面向对象技术时,我仍然是一个新手,并且在不知道究竟要搜索什么的情况下搜索这种特殊情况时遇到了麻烦。

谢谢!

4

2 回答 2

3

As @adamr notes in the comments, you could do this:

import other_file
other_file.treats = 12

Unfortunately, that will change the value of treats for all instances of Pet. If this doesn't work for you, and given that you can't change other_file, your best option as far as I can see is to inherit from Pet and also override eat to use e.g. self.treats.

于 2013-08-08T23:15:47.853 回答
0

您没有将其定义为类属性。

class Pet(object):
  def __init__(self, treats):
    self.treats = treats

  def eat(self):
    #

class Dog(Pet):
    def __init__(self):
        super(Dog, self).__init__()
        print self.treats
于 2013-08-08T23:21:10.147 回答