挑战Python100题(6)

100+ Python challenging programming exercises 6

Question 51

Define a class named American and its subclass NewYorker.

Hints: Use class Subclass(ParentClass) to define a subclass.

定义一个名为American的类及其子类NewYorker。

提示:使用class Subclass(ParentClass)来定义子类。

Solution:

class American:  
    def __init__(self, name, age):  
        self.name = name  
        self.age = age  
  
    def introduce(self):  
        return f"Hello, my name is {self.name} and I am {self.age} years old."  
  
class NewYorker(American):  
    def introduce(self):  
        return f"Yo, my name is {self.name} and I am from New York. I'm {self.age} years old."

anAmerican = American('Tom',8)
aN

猜你喜欢

转载自blog.csdn.net/boysoft2002/article/details/135219583