如何建立没有类名的实例?

问题描述 投票:0回答:1

我想在不使用类名的情况下构建Matrix类的实例,因为如果更改它,我希望它也能工作。我试图将第2行中的Matrix()替换为{self.__class__.__name__},但是没有用。想法?

class Matrix:
"""A matrices calculator for basic math actions
    Attributes:
        data(tuple of tuples): a Matrix- each line is a tuple in the major tuple """

def __init__(self, data):
    if type(data) is not tuple:
        raise ValueError("Invalid matrix")
    for tup in data:
        if len(tup) != len(data) or type(tup) is not tuple:
            raise ValueError("Invalid matrix")
    self.data = data


@staticmethod
def unity(size):
    """ unity method creates a matrix of zeros with a diagonal of ones
    args: size(int)- the size of the matrix and lines.
    returns: a matrix full of 0 and 1's diagonal
    exceptions: ValueError for non-ints"""
    if type(size) is int:
        major_list = [[1 if i == index else 0 for i in range(size)] for index in range(size)]
        sub_list = [tuple(lt) for lt in major_list]
        # converts list of lists to type Matrix. lt are the inside lists
        matrix_to_return = Matrix((tuple(sub_list)))
        return matrix_to_return
    else:
        raise ValueError("size must be an integer")
python class instance
1个回答
0
投票

不可能。从实例的类名创建实例,因为这就是实例。类的对象。您如何认为可以访问类并为其创建实例,而无需使用类名来调用它?

如果更改类名,则必须在调用它的任何地方都对其进行更改以创建实例。

© www.soinside.com 2019 - 2024. All rights reserved.