0

Does Python have any syntax that allows you to create an instance of a class and set property values on it within the same statement

You can do this in C# like this

StudentName student2 = new StudentName
{
    FirstName = "Craig",
    LastName = "Playstead",
};

Is there an equivalent in Python?

4
  • 1
    You can define defaults in __init__ method which is constructor equivalent Commented Nov 29, 2018 at 11:01
  • I need to be able to set specific values for each instance, being able to do this in a single statement would greatly simplify my code. Commented Nov 29, 2018 at 11:04
  • check out _slots_ stackoverflow.com/a/28059785/1344855 Commented Nov 29, 2018 at 11:06
  • @toefftoefftoeff __slots__ is an advanced feature that's very rarely needed in real life. I'm not sure how it would apply here much, anyway. Commented Nov 29, 2018 at 11:11

3 Answers 3

6

Not really. The Pythonic ways to express this might be one of the following.

A regular old class

class StudentName:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

student2 = StudentName(first_name="Craig", last_name="Playstead")

(You can also add a , *, argument after self to force users to spell out the keyword names see Keyword (Named) Arguments in Python.)

A namedtuple

import collections
StudentName = collections.namedtuple("StudentName", "first_name last_name")

student2 = StudentName(first_name="Craig", last_name="Playstead")

Namedtuples also act like tuples, so you can use student2[0] to access first_name and [1] for last_name.

A dataclass (Python 3.7+)

import dataclasses

@dataclasses.dataclass
class StudentName:
    first_name: str
    last_name: str

student2 = StudentName(first_name="Craig", last_name="Playstead")

Sign up to request clarification or add additional context in comments.

2 Comments

Useful to know about dataclasses!
Thanks. I can make it worked with named parameters, I have control of the classes being created so I can add all the properties in as optional parameters. The dataclass solution looks pretty neat, but I think the 3.7 requirement is to limiting for us.
1
class StudentName:
    def __init__(self, firstname, lastname):
         self.firstname = firstname
         self.lastname = lastname


name = StudentName('firstname', 'lastname')

If you want to specifically set which property is which in the constructor:

class StudentName:
    def __init__(self, firstname='', lastname=''):
         self.firstname = firstname
         self.lastname = lastname


name = StudentName(firstname='firstname', lastname='lastname')

You can then also create a StudentName like so: StudentName(). His first and lastname would be ''.

Comments

1

You can define defaults in __init__ method which is constructor equivalent

class Student():
  def __init__(self, firstname, lastname):
    self.firstname = firstname
    self.lastname = lastname

  def __str__(self):
     return "My name is {} {}".format(self.firstname, self.lastname)

s1 = Student("John", "Smith")
print(s1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.