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)
-
2The source you're learning from seems to have been created for Java and crudely adapted for Python with only syntactical changes. The practices it teaches you, like setters for everything, are not all appropriate for Python.user2357112– user23571122017年03月29日 18:30:29 +00:00Commented Mar 29, 2017 at 18:30
-
2Also, your use of plurals in names makes no sense.user2357112– user23571122017年03月29日 18:31:37 +00:00Commented Mar 29, 2017 at 18:31
-
Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. on topic and how to ask apply here. In particular, this question is quite broad and prone to opinions. "Best practice" is not solidly defined here, and often varies among companies, projects, and programmers. For instance, since Python doesn't actually have "private" attributes, you can't enforce the get/set interface -- and a lot of my Python friends consider it to be bloat.Prune– Prune2017年03月29日 18:34:14 +00:00Commented Mar 29, 2017 at 18:34
-
I guess the plurals was a bad ide, only tried two define to different classes in a simple way. Yes, I have earlier study some Java and tryed to figure out the best way to do it in Python.nutgut– nutgut2017年03月29日 19:31:02 +00:00Commented Mar 29, 2017 at 19:31
-
I agree that best practice is broad. My question should maybe be like 'Create object in Python way'nutgut– nutgut2017年03月29日 19:34:23 +00:00Commented Mar 29, 2017 at 19:34
1 Answer 1
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
answered Mar 29, 2017 at 18:31
Daniel
42.8k4 gold badges57 silver badges82 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py