繁体   English   中英

如何在 Python 中将类的变量定义为类对象

[英]How to define a variable of a class as class object in Python

我需要定义一个类的变量一个类对象。 我该怎么做?

例如,如果我有这样的课程:

class A:
  def __init__(self, a, b):
     self.a = a
     self.b = b

我想创建另一个 B 类,它有一个变量作为 A 类的实例,例如:

class B:
  def __init__(self, c = A(), d):
     self.c = c
     self.d = d 

我该怎么做 ? 当我创建 B 类的对象时,我需要做特定的操作还是简单地将 c 声明为 A 类的对象?

class B:
  def __init__(self, a, b, d):
     self.c = A(a, b)
     self.d = d

或者

class B:
  def __init__(self, c, d):
     self.c = c
     self.d = d

或者

class B:
  def __init__(self, d):
     self.c = A(a, b)      # a and b can be values
     self.d = d

你写的大部分是有效的:

    def __init__(self, c = A(), d):
        self.c = c

但是有一个你真的想避免的“陷阱”。 A构造函数将只在def时间计算一次,而不是每次构造一个新的B对象时。 这通常不是新手程序员想要的。 该签名提到了一个可变的默认参数,通常最好避免这种情况,如果只是为了避免未来的维护人员进行一些令人沮丧的调试。

https://dollardhingra.com/blog/python-mutable-default-arguments/

https://towardsdatascience.com/python-pitfall-mutable-default-arguments-9385e8265422

相反,这样说:

class B:
    def __init__(self, c = None, d):
        self.c = A(1, 2) if c is None else c
        ...

这样,每次都会重新评估A构造函数。 (此外,最好同时提供A的两个强制参数。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM