Python Forum
class needs to refer a different class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
class needs to refer a different class
#11
i'm still a bit confused with that code. it's more about the __new__() method. i don't understand passing cls to it. all i need is a method with no args. i am reading docs for 3.7 and coding for 3.6.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#12
https://docs.python.org/3/reference/data...ct.__new__
Reply
#13
what is the difference between object and cls? what i was expecting was foo.__new__() to make a new instance of foo.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#14
(Jul-20-2021, 01:20 AM)Skaperen Wrote: what is the difference between object and cls?
from dataclasses import dataclass
 
 
@dataclass
class AClass:
    situation: bool
 
    def __new__(cls, situation: bool):
        help(cls)
        help(object)
        if situation:
            return DifferentClass(situation)
        return super().__new__(cls)
 
 
@dataclass
class DifferentClass:
    situation: bool
 
 
a_class = AClass(situation=False)
# different_class = AClass(situation=True)
# print(a_class)
# print(different_class)
Output:
Help on class AClass in module __main__: class AClass(builtins.object) | AClass(situation: bool) | | AClass(situation: bool) | | Methods defined here: | | __eq__(self, other) | | __init__(self, situation: bool) -> None | | __repr__(self) | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(cls, situation: bool) | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __annotations__ = {'situation': <class 'bool'>} | | __dataclass_fields__ = {'situation': Field(name='situation',type=<clas... | | __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or... | | __hash__ = None Help on class object in module builtins: class object | The base class of the class hierarchy. | | When called, it accepts no arguments and returns a new featureless | instance that has no instance attributes and cannot be given any. | | Built-in subclasses: | async_generator | BaseException | builtin_function_or_method | bytearray | ... and 87 other subclasses | | Methods defined here: | | __delattr__(self, name, /) | Implement delattr(self, name). | | __dir__(self, /) | Default dir() implementation. | | __eq__(self, value, /) | Return self==value. | | __format__(self, format_spec, /) | Default object formatter. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self<value. | | __ne__(self, value, /) | Return self!=value. | | __reduce__(self, /) | Helper for pickle. | | __reduce_ex__(self, protocol, /) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setattr__(self, name, value, /) | Implement setattr(self, name, value). | | __sizeof__(self, /) | Size of object in memory, in bytes. | | __str__(self, /) | Return str(self). | | ---------------------------------------------------------------------- | Class methods defined here: | | __init_subclass__(...) from builtins.type | This method is called when a class is subclassed. | | The default implementation does nothing. It may be | overridden to extend subclasses. | | __subclasshook__(...) from builtins.type | Abstract classes can override this to customize issubclass(). | | This is invoked early on by abc.ABCMeta.__subclasscheck__(). | It should return True, False or NotImplemented. If it returns | NotImplemented, the normal algorithm is used. Otherwise, it | overrides the normal algorithm (and the outcome is cached). | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __class__ = <class 'type'> | type(object_or_name, bases, dict) | type(object) -> the object's type | type(name, bases, dict) -> a new type
object is the built in object that all classes subclass
cls is the parameter used in a class __new__ method it is a pointer to the class itself just like self is a pointer to the instance of a class.

(Jul-20-2021, 01:20 AM)Skaperen Wrote: what i was expecting was foo.__new__() to make a new instance of foo.
Where does foo come into it? you have not mentioned foo until now or given a basic example of your classes yet or modified my version to your needs or closest you feel you can to your needs.
Reply
#15
I think there is way too much code in _zio.__init__() and most of this code is not directly related to the instance being created. Only three attributes are set in this method, namely self.realname, self.tmpname, self.allfiles. I think most of this method's code should be written in an external "factory" function named for example _new_io() and the structure could be
def _new_io(name=None,mode='r',compresslevel=None,*,
            buffering=-1,
            compress=None,
            closefd=True,
            check=-1,
            encoding=None,
            errors=None,
            format=None,
            newline=None,
            tempname=False,
    ):
    ...
    zio = _zio(realname, tmpname, allfiles)
    ...
    return zio

class _zio(io.IOBase):
    def __init__(self, realname, tmpname, allfiles):
        self.realname = realname
        self.tmpname = tmpname
        self.allfiles = allfiles
    ...
zopen() and ztopen() would invoke _new_io() instead of _zio() and the advantage is that the body of _new_io() can now incorporate special cases where it returns something different from a _zio() instance, perhaps another instance of io.IOBase().
Reply
#16
normally foo just means something arbitrary. in this case it was the class the caller was expecting to get an instance of, the method which would choose to make an instance of some other class that caller does not know about.

a poor example of this is a class that opens a file that may, or may not, be filtered in some way. if the method determines that no filtering is needed, that the objective is to return an instance of file class instead of an instance of itself (it would do the filtering, if needed). i give this example as a way to understand what i'm trying to do, not the details to find some other way to do this, i was originally trying to do this with a front end function to decide which class is needed.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#17
Skaperen Wrote:the objective is to return an instance of file class instead of an instance of itself
I'm not sure I understand what you are trying to do but calling a class' constructor to get an object of a different type seems completely inappropriate. More specifically, __init__() methods don't even use the return statement in Python.

You could achieve the same (misleading) effect by overwriting the name of the class

class Foo:
    pass

class Bar:
    pass

_c_foo = Foo

def Foo(condition):
    if condition:
        return _c_foo()
    else:
        return Bar()

if __name__ == '__main__':
    f = Foo(0) # returns a Bar instance while pretending to create a Foo instance.
Reply
#18
the intention is to provide an instance that is appropriate for the particular file. if an instance of io.IOBase is appropriate, that's what should be returned. but, an instance of this class may be appropriate.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#19
This is not the role of an __init__() method. The purpose of this method is to initialize the state of a new instance of the class where it belongs.
ndc85430 likes this post
Reply
#20
right.

i am thinking i should just have functions zopen, ztopen, and topen to pass the varying parameters to the class. the difficulty is the complex relation of the file name to the sequence of (de)compression opens to be done for files that are multiply compressed. i know i can set that up in a function, but making it all into a single class that can close() them all in the right order is really messy.

and, i am looking at making zpopen() that sets up the compress as process for better performance in certain cases.

and, yes, i really do have a few multiply compressed files. i originally was wondering in any of the (de)compression classes have issues with multiple instances of itself for the same file. they shouldn't. they didn't. gzip.open() really can open against another instance of itself (for "foo.gz.gz") just fine.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  is ValueError a class? Skaperen 11 2,577 Mar-29-2023, 02:25 AM
Last Post: Skaperen
  extracting a function/class/method from code Skaperen 5 2,242 Mar-30-2022, 12:13 AM
Last Post: Skaperen
  first class objects Skaperen 0 944 Jan-22-2022, 02:53 AM
Last Post: Skaperen
  returning a different class Skaperen 4 2,117 Oct-20-2021, 12:51 AM
Last Post: Skaperen
  getting my head arounnd __enter__() for my new class Skaperen 5 2,512 Nov-30-2020, 09:46 AM
Last Post: Gribouillis
  find the class for indexed counting Skaperen 4 2,001 Sep-29-2020, 03:26 AM
Last Post: Skaperen
  namespaces when defining a class Skaperen 3 2,119 Jul-03-2020, 06:34 PM
Last Post: Gribouillis
  a file-like class implementation Skaperen 2 2,050 Apr-22-2020, 02:59 AM
Last Post: Skaperen
  making a generator class? Skaperen 2 2,075 Apr-01-2020, 12:34 AM
Last Post: Skaperen
  single-instance class Skaperen 3 2,524 Mar-05-2020, 12:47 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020