在Python中跨继承使用类变量

huangapple go评论63阅读模式
英文:

Use a class variable across inheritance in Python

问题

以下是代码的中文翻译部分:

# 在Python中,我想要定义一个顶层类,该类可以依赖于一个类变量。然后,我想要能够在类级别更改该变量,用于该类的子类,但仍继承使用该变量的功能。

# 一般而言,我的父类具有依赖于配置变量的一些函数。所有我的子类使用相同的函数,但具有不同的参数。我希望能够在类级别更改参数。

# 作为最简单的示例,以下是两个类,其中“Parent”根据“my_global”定义函数,然后“Child”尝试更改该变量(但失败)。

class Parent():
    my_global = "parent"

    def __init__(self):
        pass

    def printmg(self):
        print(Parent.my_global)

class Child(Parent):
    my_global = "child"

my_parent = Parent()
my_parent.printmg()
my_child = Child()
my_child.printmg()

这将输出:

parent
parent

而我希望它输出:

parent
child

我不想将变量保留在对象级别(即self.my_global = "child"),也不想为子类重写函数。

英文:

In Python, I want to define a top level class that can depend on a class variable. Then I want to be able to change that variable at the class level, for children of the class, but still inherit the functionality that uses that variable.

In general, my Parent class has some functions that depend on configuration variables. All my child classes use those same functions, but with different parameters. I would like to be able to change the parameters at the class level.

As the simplest example, here are two classes where the Parent defines functions in terms of my_global, then the Child attempts to change that variable (but fails)

class Parent():
    my_global = "parent"
    
    def _init_(self):
        pass

    def printmg(self):
        print(Parent.my_global)


class Child(Parent):
    my_global = "child"


my_parent = Parent()
my_parent.printmg()
my_child = Child()
my_child.printmg()

This outputs

parent
parent

While I would like it to output

parent
child

I don't wan't to keep the variables at the object level (i.e. self.my_global = "child"), or to rewrite the function for the child.

答案1

得分: 1

如果您不需要实例方法,请将 printmg 定义为 classmethod

@classmethod
def printmg(cls):
    print(cls.my_global)
英文:

If you don't need an instance method define printmg as classmethod:

@classmethod
def printmg(cls):
    print(cls.my_global)

答案2

得分: 1

print(Parent.my_global)这一行更改为print(self.my_global)

self操作符代表当前类。因此像这样打印会起作用。

英文:

Change the line print(Parent.my_global) to print(self.my_global).

The self operater represents the current class. So printing like this will work.

huangapple
  • 本文由 发表于 2023年2月10日 03:10:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定