Define a class, which has a class parameter and the same instance parameter

Question:

Define a class, which has a class parameter and the same instance parameter.

Hints:

  • Define an instance parameter, need to add it in the init method
  • You can init an object with a construct parameter or set the value later

Solution:

class Person:
    # Define the class parameter "name"
    name = "Person"
    
    def __init__(self, name = None):
        # self.name is the instance parameter
        self.name = name

jeffrey = Person("Jeffrey")
print "%s name is %s" % (Person.name, jeffrey.name)

nico = Person()
nico.name = "Nico"
print "%s name is %s" % (Person.name, nico.name)
Code language: Python (python)

Leave a Comment