嵌套类:如何在Python中将一个类放入另一个类中
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了嵌套类:如何在Python中将一个类放入另一个类中相关的知识,希望对你有一定的参考价值。
class DisneyCharacter(): # This variable holds the name for the class DisneyCharacter name = "" class Duck(): # This variable holds the name for the class Duck name = "" def __init__(self, name = None): """ Constructor for the class Duck """ # If the user doesn't specify a second name, "Duck" will be chosen if (name is None): name = "Duck" self.name = name def getName(self): """ Returns the name stored in the class Duck """ return self.name def __init__(self, name = None, secondName = None): """ Constructor for the class DisneyCharacter """ # If the user doesn't specify a name, "Donald" will be chosen if (name is None): name = "Donald" # Creates a new instance of Duck newDuck = DisneyCharacter.Duck(secondName) # This will join together the names from the classes DisneyCharacter and Duck self.name = name + " " + newDuck.getName() def getName(self): """ Returns the name stored in the class DisneyCharacter """ return self.name # Creates an instance of the class DisneyCharacter donald = DisneyCharacter() # Writes "Donald Duck" print(donald.getName()) # Writes "Daisy Duck" daisy = DisneyCharacter("Daisy") print(daisy.getName()) # Writes "Scrooge McDuck" unclescrooge = DisneyCharacter("Scrooge", "McDuck") print(unclescrooge.getName())
以上是关于嵌套类:如何在Python中将一个类放入另一个类中的主要内容,如果未能解决你的问题,请参考以下文章