简体   繁体   English

如何对具有不同属性的超类使用超级方法

[英]How to use super method for a superclass with different attributes

I have a class of characters, they have a name, description, age and size (my attributes).我有一个 class 字符,它们有名称、描述、年龄和大小(我的属性)。 Then I have a subclass squad that inherits character.然后我有一个继承字符的子类小队。 Each squad has a name, leader, member1, and member2.每个小队都有一个名称、领导者、成员 1 和成员 2。 (My squad attributes). (我的小队属性)。 I am unsure of how to set this up as the two classes share no attributes.我不确定如何设置它,因为这两个类不共享任何属性。 All the examples and lessons I find online about class inheritance uses two classes with shared attributes.我在网上找到的所有关于 class inheritance 的示例和课程都使用两个具有共享属性的类。 (such as a furniture class that has the name and price of furniture with a subclass chairs, that has the same name and price, but also has a seat depth, perhaps). (例如家具 class 具有家具的名称和价格以及子类椅子,具有相同的名称和价格,但也可能具有座椅深度)。

I am just unsure of how my super().我只是不确定我的 super(). init should be set up (or if I even need one).应该设置init (或者如果我什至需要一个)。

I also need to set up a str method for my squad that uses the str method from character.我还需要为我的小队设置一个str方法,该方法使用字符中的str方法。 I have a hard time wrapping my head around how to do this as well, as I have a squad being passed in as the parameter, so what will the program do when it gets to the part of the super().我也很难弄清楚如何做到这一点,因为我有一个小队作为参数传入,所以当程序到达 super() 的部分时会做什么。 str that tells it to print the character's age, if all it has is my squad name and squad members? str告诉它打印角色的年龄,如果它只有我的小队名称和小队成员?

As you describe it: it is better to have member1 and member2 as characters, and no inheritance.正如您所描述的:最好将 member1 和 member2 作为字符,而不是 inheritance。

A squad is composed of 2 or more charcaters, so it cannot inherint the character class.一个小队由 2 个或更多字符组成,因此它不能继承字符 class。

For inheritance use case: if you have different types of characters you could have lets say Medics and Soldiers classes inheriting from characters.对于 inheritance 用例:如果您有不同类型的角色,您可以假设 Medics 和 Soldiers 类从角色继承。

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

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