Python Class Constructors and Instance Initialization

Поділитися
Вставка
  • Опубліковано 13 гру 2024

КОМЕНТАРІ • 8

  • @LuigiBrotha
    @LuigiBrotha Місяць тому

    Why is isinstance to store the class around 11:03 . Type would be much clearer here

  • @Squash101
    @Squash101 3 місяці тому

    is there some sort of playlist for this?

  • @eles108
    @eles108 2 роки тому +1

    Thanks

  • @pythonicman6074
    @pythonicman6074 2 роки тому

    انت مبدع

  • @orangasli2943
    @orangasli2943 2 роки тому

    I believe there is no initializer list-like where you just need to pass in the constant value to the constructor as parameters..
    Let say I have a class "Point" which has x,y,z to be passed in the Point to constructor..it is fine..
    But then if I make a class "Triangle"
    I want to take three "Points" with it
    When defining Triangle object I have difficulty passing in the parameters like in c++ using the initializer list with the '{' '}' and pass in the constant/literal accordingly..but there are no options like this in python..
    I need to give the name first to all the points before I can pass it to the triangle constructor..
    Is there any way I can do this?
    I tried using the *args by python but it seems it can only used for one tuple not more than that..I requested three tuples but it says it cannot do it..
    I guess I want to write code back in c++

    • @rdean150
      @rdean150 Рік тому +2

      You can indeed do this with *args.
      class Point:
      def__init__(self, x, y, z):
      self.x = x
      self.y = y
      self.z = z
      def __repr__(self):
      return f"Point({self.x}, {self.y}, {self.z})"
      class Triangle:
      def __init__(self, *points):
      if len(points) != 3:
      raise ValueError()
      self.points = points
      t = Triangle( *[Point(1, 2, 3), Point(4, 5, 6), Point(7, 8, 9)] )
      for point in t.points:
      print(point)

    • @rdean150
      @rdean150 Рік тому +2

      You can do the same with named attributes by using **kwargs instead of *args.
      But the important thing here is that this requires the __init__ to accept the arguments, which is not quite the same as initializer lists, which allow arbitrary assignment of attributes, regardless of constructor signature.
      There are succint ways if doing arbitrary names assignments in python also, but still not exactly like initializer lists.

  • @serychristianrenaud
    @serychristianrenaud 2 роки тому

    Thank