Reputation: 1
I'm learning Python and recently started with the OOP part. I know there are different ways to create objects but I do not know what way I should aim at.
Create objects with arguments or without arguments? Then I do understand the best way to change the attributes is with method calls.
Code:
class Human(object):
def __init__(self):
self.name = ''
self.age = 0
def set_name(self, name):
self.name = name
def set_age(self, age):
self.age = age
class Humans(object):
def __init__(self, name, age):
self.name = name
self.age = age
def set_names(self, name):
self.name = name
def set_ages(self, age):
self.age = age
# Create object without arguments
boy = Human()
boy.set_name('Peter')
boy.set_age(30)
# Or create object with arguments
girl = Humans('Sandra', 40)
Upvotes: 0
Views: 60
Reputation: 42778
An object should be in an usable state after creation. That said, a human with no name and no age is not useful. So the second implemention is preferred. Another thing is, that you don't need setters in python, which reduces the class to
class Humans(object):
def __init__(self, name, age):
self.name = name
self.age = age
Upvotes: 2